【问题标题】:Using vuex inside a manually-mounted vue component在手动安装的 vue 组件中使用 vuex
【发布时间】:2017-11-11 20:05:26
【问题描述】:

我正在使用 Vue.extend 手动将组件安装到动态元素,如下所示:

import Vue from 'vue';
import MyComponent from 'MyComponent.vue';

const MyComponentConstructor = Vue.extend(MyComponent);
const MyComponent = new MyComponentConstructor({
    propsData: {
        foo: 123,
    },
}).$mount('#mount-point');

当我以这种方式手动挂载组件时,我无法在MyComponent.vue内部使用vuex。:

// (inside MyComponent.vue)
this.$store.commit('setSomething', true);

我明白了:

未捕获的类型错误:无法读取未定义的属性“提交”

当然vuex 在其他正常组件中已设置并正常工作。有什么我可以传递给构造函数以使其工作的东西吗?

【问题讨论】:

    标签: vue.js vue-component vuex


    【解决方案1】:

    将存储作为选项的一部分传递给构造函数。

    import store from "path/to/store"
    
    const MyComponent = new MyComponentConstructor({
        store,
        propsData: {
            foo: 123,
        },
    }).$mount('#mount-point');
    

    【讨论】:

    • 哇,就这么简单!谢谢!看起来我也可以从父组件传递store: this.$store,所以我什至不必导入商店!
    【解决方案2】:

    我参加聚会有点晚了,但仍然有插话的冲动。 我发现的最佳方法是如果您可以访问它,则将 parent 键作为实际父级传递(它通常是安装父级上的 this)。所以你会这样做:

    const MyComponent = new MyComponentConstructor({
        parent: this,
        propsData: {
            foo: 123,
        },
    }).$mount('#mount-point')
    

    您可以在已挂载的组件实例中访问其他有用的全局变量(如$route$router,当然还有$store)。这也正确地通知Vue 组件层次结构使MyComponent 在开发工具中可见。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2018-04-17
      • 2019-05-16
      • 2021-06-13
      • 2010-12-19
      • 2020-12-07
      • 1970-01-01
      • 2020-05-04
      • 2019-11-02
      相关资源
      最近更新 更多