DMack
DMack

Reputation: 949

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?

Upvotes: 11

Views: 3142

Answers (2)

Awoyemi Afeez Damola
Awoyemi Afeez Damola

Reputation: 51

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.

Upvotes: 5

Bert
Bert

Reputation: 82449

Pass the store as part of the options to the constructor.

import store from "path/to/store"

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

Upvotes: 13

Related Questions