【问题标题】:Sharing data between components in vue.js在 vue.js 中的组件之间共享数据
【发布时间】:2019-08-14 05:53:54
【问题描述】:

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

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

这是我目前得到的...

组件 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 

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

【问题讨论】:

  • Vuex 怎么样?
  • 也许吧。有什么例子吗?访问您的数据似乎是一项微不足道的任务......

标签: vue.js components sharing


【解决方案1】:

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

嗯,你可以使用Vue.mixins来实现。

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

Mixins 官方docs

希望这会有所帮助!

【讨论】:

    【解决方案2】:

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

    npm install vuex --save

    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')
    

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

    显然,您可以使用 getter 和操作以及其他东西,但这会让您继续前进,一旦您熟悉并了解 Vuex 商店的工作原理,您就可以阅读和修改它。

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2021-11-11
      • 2020-08-31
      • 2016-05-04
      • 2018-10-12
      相关资源
      最近更新 更多