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

Using vuex inside a manually-mounted vue component

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

我明白了:

Uncaught TypeError: Cannot read property 'commit' of undefined

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

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

import store from "path/to/store"

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

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

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

您将可以访问已安装组件实例中的其他有用的全局变量(例如 $route$router,当然还有 $store)。这也正确地告知 Vue 组件层次结构,使 MyComponent 在 dev-tools 中可见。