Import Vue or other components into child components

0

I have an application in VueJs2, in which I have an app.js, where I instantiate Vue and do the imports (Templates, plugins, etc). It turns out that some plugins / libs I can usually use inside child components (axios, for example), others I need to do the 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 the axios inside the components, normally. No need to "re-import" into the component. It stays global.

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

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

In the above context, if I try to use a Vuex, I would not be able to. As already mentioned, I could (and can) use the axios or another 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>

Mandatoryly I need to enter the Vue, inclusive. If I only import the Vuex, it accuses error in the lack of Vue.

The Vuex is just one example. Occurs with other libs. I'm having this difficulty and I do not want to re-import the plugins / libs ... unless that's really the right way (and I'd like to know why in the app.js does not stay global).

Thank you

    
asked by anonymous 04.01.2018 / 17:28

2 answers

1

You can pass your store from Vuex into the creation of the app in the same way that the router passes. 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, inside a component method, you can refer to the store with this.$store .

    
05.01.2018 / 03:08
0

Vue.use makes the plugin become "part" of Vue, becoming global (I believe that's what happens). So you "used" var to be available on the Vue's own instance. In case of Vuex you can access with this. $ Store In the case of Router you can access with this. $ Router

    
05.01.2018 / 01:16