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

在vue.js中的组件之间共享数据,vue.js,components,sharing,Vue.js,Components,Sharing,我在一个组件中获得了一个数据数组,我想在另一个组件中访问该数组,但无法正确获取它 我的想法是将组件1导入到组件2中,并认为我可以通过这种方式访问数据,但它不起作用 这是我到目前为止得到的 组件1: export default { data() { return { info: [ { id: 1, title: "Title One" }, { id: 2,

我在一个组件中获得了一个数据数组,我想在另一个组件中访问该数组,但无法正确获取它

我的想法是将组件1导入到组件2中,并认为我可以通过这种方式访问数据,但它不起作用

这是我到目前为止得到的

组件1:

export default {
  data() {
    return {
      info: [
        {
          id: 1,
          title: "Title One"
        },
        {
          id: 2,
          title: "Title Two"
        },
<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:

export default {
  data() {
    return {
      info: [
        {
          id: 1,
          title: "Title One"
        },
        {
          id: 2,
          title: "Title Two"
        },
<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 

{{item.title}
从“./视图/ComponentOne”导入ComponentOne;
导出默认值{
组成部分:{
成分
},但在这之后我有点迷路了

如果有人能为我指出正确的方向,我将不胜感激!

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

npm安装vuex--保存

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

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')
要在获取信息时更新存储,可以从任何组件使用
this.$store.commit('example/set',infoArray)
,其中第一个参数遵循
模块名称/变异函数名称的模式,第二个参数是要更新的“新状态”

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

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

显然,您可以使用getter、actions和其他东西,但这会让您继续,您可以在熟悉并理解Vuex应用商店的工作原理后阅读并修改它。

假设您不想使用任何其他状态管理,如
Vuex
,那么您可以使用mixin进行共享

好的,您可以使用
Vue.mixins
来实现它

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

混音官


希望这有帮助!

Vuex呢?也许吧。有什么例子吗?访问您的数据似乎是一项非常琐碎的任务。。。