11

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?

2 Answers 2

13

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, simple as that! Thanks! It looks like I can also pass store: this.$store from the parent component so I don't even have to import the store!
5

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.

1 Comment

This is a better approach because, in most case, we just want to create a new child component rather than a new App. By using parent prop, the new component will extends all features we added to App.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.