在vue.js中的组件之间共享数据

时间:2019-03-23 11:29:11

标签: vue.js components sharing

我在一个组件中获取了一个数据数组,但我想在另一个组件中访问它

我的想法是只导入第二个组件中的第一个组件,并认为我可以以这种方式访问​​数据,但它没有用。

这是我到目前为止得到的...

组件1:

export default {
  data() {
    return {
      info: [
        {
          id: 1,
          title: "Title One"
        },
        {
          id: 2,
          title: "Title Two"
        },

组件2:

<template>
  <div>
      <div v-for="item in info" v-bind:key="item.id">
         <div>{{ item.title }} </div>
      </div>
  </div>
</template> 

<script>
import ComponentOne from "../views/ComponentOne ";

export default {
  components: {
    ComponentOne 
  },  But after this I am a bit lost 

谁能指出我的正确方向,将不胜感激!

2 个答案:

答案 0 :(得分:1)

为了访问共享数据,最常见的方法是使用Vuex。我将带您了解带有模块系统的超级基础知识,因为它需要一点阅读。

npm install vuex --save

store目录中创建名为src的新文件夹。

src / store / index.js

import Vue from 'vue'
import Vuex from 'vuex'
import example from './modules/example'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    example // replace with whatever you want to call it
  }
})

src / main.js

// add to your imports
import store from './store/index'
...

// Change your Vue instance init
new Vue({
  router,
  store, // <--- this bit is the thing to add
  render: h => h(App)
}).$mount('#app')

/src/store/modules/example.js

// initial state
const state = {
  info: []
}

// getters
const getters = {}

// actions
const actions = {
}

// mutations
const mutations = {
  set (state, newState) {
    state.info.splice(0)
    state.info.push.apply(state.info, newState)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

要在获取信息时更新商店,可以从任何组件使用this.$store.commit('example/set', infoArray),其中第一个参数遵循module name/mutation function name的模式,第二个参数是所需的“新状态”已更新。

要访问存储中的数据,可以从组件中将其作为计算属性来访问:

computed: {
  info () {
    return this.$store.state.example.info
  }
}

很明显,您可以使用吸气剂,动作和其他东西,但这可以助您一臂之力,一旦您适应并了解其工作原理,就可以阅读和修改Vuex商店。

答案 1 :(得分:0)

让我们说,如果您不想使用任何其他状态管理(例如vuex),那么可以使用mixins进行共享。

好吧,您可以使用Vue.mixins来实现。

  

Mixin是分配Vue组件可重用功能的灵活方法。 mixin对象可以包含任何组件选项。当组件使用混合时,mixins中的所有选项都将“混合”到组件自己的选项中。

Mixins官方docs

希望这会有所帮助!