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

问题描述 投票:0回答:2

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

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

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

第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 

任何人都可以指出我正确的方向,非常感谢!

vue.js components sharing
2个回答
1
投票

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

npm install vuex --save

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

SRC /存储/ 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')

/双人床/store/modules/example.就是

// 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
  }
}

显然你可以使用getter和动作以及其他东西,但是这会让你前进,一旦你感到舒服并且理解它是如何工作的,你就可以阅读并修改Vuex商店。


0
投票

假设您不想使用像vuex这样的任何其他州管理,那么您可以分享使用mixins。

那么,你可以使用Vue.mixins实现它。

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

Mixins官方docs

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.