I'm manually mounting a component to a dynamic element using Vue.extend
like this:
import Vue from 'vue';
import MyComponent from 'MyComponent.vue';
const MyComponentConstructor = Vue.extend(MyComponent);
const MyComponent = new MyComponentConstructor({
propsData: {
foo: 123,
},
}).$mount('#mount-point');
When I manually mount a component in this way, I can't use vuex
inside MyComponent.vue
.:
// (inside MyComponent.vue)
this.$store.commit('setSomething', true);
I get this:
Uncaught TypeError: Cannot read property 'commit' of undefined
Of course vuex
is set up and working fine in the other normal components. Is there something I can pass to the constructor to get it to work?
I'm a little late to the party, still felt the urge to chime this in.
The best approach I've found is to pass the parent
key as the actual parent if you have access to it (it'll be this
on the mounting parent usually). So you'll do:
const MyComponent = new MyComponentConstructor({
parent: this,
propsData: {
foo: 123,
},
}).$mount('#mount-point')
You'll have access to other useful globals (like $route
, $router
, and of course $store
) within the mounted component instance. This also properly informs Vue
of the component hierarchy making MyComponent
visible in the dev-tools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With