Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vuex inside a manually-mounted vue component

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?

like image 784
DMack Avatar asked Jun 09 '17 17:06

DMack


1 Answers

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.

like image 104
Awoyemi Afeez Damola Avatar answered Sep 19 '22 11:09

Awoyemi Afeez Damola