【问题标题】:How to share the state from vuex store to all child components如何将状态从 vuex 存储共享到所有子组件
【发布时间】:2018-10-21 03:22:38
【问题描述】:

我正在创建一个包含子组件列表的自定义表单组件。 因此,在我的父组件中,我添加了 vuex 存储,其中包含我想在子组件之间共享的状态(数据)。我所有的组件都是单页组件。

// CustomFormComponent.vue (parent component)
<template>
  <div>
   <form @submit='checkStateOfChildren()' >
     // Do a for loop on mySchema in store and dynamically detect the 
     // custom component based on individual node item in mySchema[]

     forEach Node in $store.mySchema[]
       render a custom component 
         // E.g <custom_text> or <custom_radio> ....
     ...
     <button type='submit'>Submit</button>
   </form>
  </div>
<template>

import store from '../store'; // Vuex Store
export default {
 store,

   created() {
   // ... populate store schema and model object to render the form elements

  },

  methods: {
     // Do the validation on the store.state.myModel and if everything is OK ... 
    // then do a post to backend
     checkStateOfChildren() {}
  }
}

而我的店铺如下所示

export default new Vuex.Store({
     state: {
        mySchema: {[ {custom_text_area schema}, {some component schema ...}, ...]}, 
        myModel: { custom_text_area_model, ...}
    },

    ... actions, mutations etc 
}

那么每个孩子如何从 VueEx 商店访问 mySchema 和 myModel 呢?

如何在子自定义组件中实现双向状态绑定?

【问题讨论】:

  • 看来我已经找到了解决方案。我所要做的就是将 store 包含在我的父组件中,它将自动注入到所有子组件中,您可以通过 this.$store 之类的方式引用它(使用它)。那是多么优雅。为了更好的状态管理,我想我可以在每个子组件中导入 mapState、mapGetters、mapActions。

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

我通常为此使用computed properties

我进行了设置,以便计算属性将在 get() 函数中从 Vuex 读取,然后您可以使用 set() 将其提交回 Vuex。

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 2017-11-23
    • 2021-04-18
    • 2018-05-24
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多