【问题标题】:dynamic vue component access to vuex动态vue组件访问vuex
【发布时间】:2021-06-14 15:11:43
【问题描述】:

我正在使用以下代码来动态创建 vue 组件。我希望他们与 vuex 商店通信,但看起来他们无法访问它。有谁知道如何解决这个问题?

let module = this.modules.find(m => m.name === name)
const ModClass = Vue.extend(module.component);
const modInstance = new ModClass({
  propsData: {
    client: this.client,
  }
});
modInstance.$mount();
modInstance.$on('close', () => {
  modInstance.$destroy(true);
  (modInstance.$el).remove();
})
this.$refs.panels.appendChild(modInstance.$el);

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    From the docs:

    为了在你的 Vue 组件中访问 this.$store 属性,你需要将创建的 store 提供给 Vue 实例。

    Vuex 有一种机制,可以使用 store 选项将 store 从根组件“注入”到所有子组件中。

    因此,在您的示例中,这将在这里:

    const modInstance = new ModClass({
      propsData: {
        client: this.client,
      },
      store: yourVuexInstanceHere
    });
    

    您正在制作 Nuxt 插件吗?如果是这样,您可以通过从上下文中解构它来访问您的商店实例。

    export default ({ app: { store } }, inject) => {
    
      // your code...
    
      const modInstance = new ModClass({
      propsData: {
        client: this.client,
        },
        store: store
      });
    
      // your code...
    
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2020-12-07
      • 2020-12-29
      • 2020-04-28
      • 2020-05-01
      • 2019-04-04
      • 1970-01-01
      • 2021-03-16
      • 2017-07-25
      相关资源
      最近更新 更多