我正在使用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中使用MyComponent.vue。
// (inside MyComponent.vue)
this.$store.commit('setSomething', true);我明白了:
未定义的TypeError:无法读取未定义的属性“提交”
当然,vuex在其他正常组件中是很好的设置和工作。有什么东西我可以传递给构造函数让它工作吗?
发布于 2017-06-09 17:57:55
将存储作为选项的一部分传递给构造函数。
import store from "path/to/store"
const MyComponent = new MyComponentConstructor({
store,
propsData: {
foo: 123,
},
}).$mount('#mount-point');发布于 2020-10-02 15:09:57
我去派对有点晚了,还觉得有冲动要插嘴。我发现的最佳方法是将parent键作为实际的父键传递给您,如果您能够访问它(通常是挂载父服务器上的this )。所以你要做:
const MyComponent = new MyComponentConstructor({
parent: this,
propsData: {
foo: 123,
},
}).$mount('#mount-point')您可以在挂载的组件实例中访问其他有用的全局(如$route、$router,当然还有$store)。这也适当地通知Vue组件层次结构,使MyComponent在开发工具中可见。
https://stackoverflow.com/questions/44463984
复制相似问题