Detailed explanation of Vue building Vuex environment

  • 2021-12-05 05:20:06
  • OfStack

Summary of directory building Vuex environment

Building an Vuex environment

In src Create 1 folder under the directory store , in store Create 1 in the folder index.js Documents

index.js Used to create the core store in Vuex


//  scr/vuex/index.js
 //  Introduce Vuex
import Vuex from 'vuex'
 //  Used to respond to actions in components 
const actions = {}
//  Used to manipulate data 
const mutations = {}
//  Used to store data 
const state = {}
 //  Create store
const store = new Vuex.Store({
    actions,
    mutations,
    state
})
 //  Export store
export default store

//  main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store/index'
 Vue.use(Vuex)
 new Vue({
    render:h => h(App),
    store
}).$mount('#app')

But there will be an error:

[vuex] must call Vue.use(Vuex) before creating a store instance

[vuex] must be called before creating an store instance Vue.use(Vuex)

Reason: When we import store, we first execute the code that imported the file, so when we execute the following code, the imported file has already been executed

In this case, then we exchange import store from './store/index' , Vue.use(Vuex) Two lines of code

But the actual result is: [vuex] must call Vue.use(Vuex) before creating a store instance , still report errors

Reason: This is the scaffold parsing import statement problem, import will be introduced into the file in advance, placed at the beginning of the code, is also the first to parse, and then parse the file code

Correct writing:


//  scr/store/index.js
 //  Introduce Vuex And Vue
import Vuex from 'vuex'
import Vue from 'vue'
 //  Application Vuex Plug-ins 
Vue.use(Vuex)
 //  Used to respond to actions in components 
const actions = {}
//  Used to manipulate data 
const mutations = {}
//  Used to store data 
const state = {}
 //  Create store
const store = new Vuex.Store({
    actions,
    mutations,
    state
})
 //  Export store
export default store

//  main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
 new Vue({
    render:h => h(App),
    store
}).$mount('#app')

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: