首页 文章

在手动安装的vue组件中使用vuex

提问于
浏览
2

我正在使用 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);

我明白了:

未捕获的TypeError:无法读取undefined的属性'commit'

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

1 回答

  • 4

    将商店作为选项的一部分传递给构造函数 .

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

相关问题