Import Vue or other components into child components

Asked

Viewed 846 times

0

I have an application in Vuejs2, in which I have an app.js, where I install Vue and make the Imports (Templates, plugins, etc). It turns out that some plugins/libs I can normally use inside child components (Xios, for example), while others I need to import/use again inside the component. Example: Vuex.

My app.js

//Vue
import Vue from 'vue'

//Axios
import axios from 'axios'

//Vuex
import Vuex from 'vuex'
Vue.use(Vuex)

... 


//Main
new Vue({
    router,
    render: h => h(App)
}).$mount('#app')

In this context I can use Axios inside the components, normally. No need to "re-import" inside the component. It is global.

Any component (imported into my app.js and running)

<script>
import BtnAction from './../helper/BtnAction.vue';
export default {
    ...
}
</script>

In the context above, if I try to use a Vuex, I could not. As already mentioned, I could (and can) use the Xios or other lib.

That way it works

<script>
import BtnAction from './../helper/BtnAction.vue';
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default {
     ...
}
</script>

Obligatorily I need to insert Vue, including. If I only import Vuex, it accuses error in the absence of Vue.

Vuex is just one example. It occurs with other libs. I’m having this difficulty and I don’t want to re-import the plugins/libs... unless this is really the right way (and I’d like to know why the app.js isn’t global).

Thank you

2 answers

1


You can pass your store of Vuex in the creation of the app in the same way that passes the router. Something like this:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = Vuex.Store({
    state: {
        propriedade: 'valor'
    },
    mutations: {
        // ...
    }
});

const app = new Vue({
    store // ou store: store
}).$mount('#app');

Then, within a component method, you can refer to the store like this with this.$store.

  • Great answer! Thank you.

  • Just one question: vc says "within a component method" ... I could use a store outside a method (Mounted, created, etc.) ?

  • 1

    Yes, from anywhere where you can access the this of the @Marcogarcia component

0

Vue.use makes the plugin becomes "part" of Vue, becoming global (I believe that’s what happens). So that you "used" to be available in the very instance of Vue. In the case of Vuex Voce you can access with this. $store In the case of Voce Router you can access with this. $router

Browser other questions tagged

You are not signed in. Login or sign up in order to post.