Vue 搭建Vuex環(huán)境詳解
搭建Vuex環(huán)境
在src目錄下創(chuàng)建一個文件夾store,在store文件夾內(nèi)創(chuàng)建一個index.js文件
index.js用于創(chuàng)建Vuex中最核心的store
// scr/vuex/index.js
// 引入Vuex
import Vuex from 'vuex'
// 用于響應(yīng)組件中的動作
const actions = {}
// 用于操作數(shù)據(jù)
const mutations = {}
// 用于存儲數(shù)據(jù)
const state = {}
// 創(chuàng)建store
const store = new Vuex.Store({
actions,
mutations,
state
})
// 導(dǎo)出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')
但是這樣會出現(xiàn)報錯:
[vuex] must call Vue.use(Vuex) before creating a store instance
意思為:[vuex] 在創(chuàng)建 store 實例之前必須調(diào)用 Vue.use(Vuex)
原因:在我們導(dǎo)入store的時候,先執(zhí)行引入文件的代碼,所以在執(zhí)行以下代碼時,引入的文件已經(jīng)被執(zhí)行了
既然這樣子,那么我們交換import store from './store/index',Vue.use(Vuex)兩行代碼
可是實際的結(jié)果是:[vuex] must call Vue.use(Vuex) before creating a store instance,依舊報錯
原因:這是腳手架解析import語句的問題,會將import引入的文件提前,放在代碼的最開始,也是最開始解析,然后解析本文件的代碼
正確的寫法:
// scr/store/index.js
// 引入Vuex和Vue
import Vuex from 'vuex'
import Vue from 'vue'
// 應(yīng)用Vuex插件
Vue.use(Vuex)
// 用于響應(yīng)組件中的動作
const actions = {}
// 用于操作數(shù)據(jù)
const mutations = {}
// 用于存儲數(shù)據(jù)
const state = {}
// 創(chuàng)建store
const store = new Vuex.Store({
actions,
mutations,
state
})
// 導(dǎo)出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')
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
vue v-for 點擊當前行,獲取當前行數(shù)據(jù)及event當前事件對象的操作
這篇文章主要介紹了vue v-for 點擊當前行,獲取當前行數(shù)據(jù)及event當前事件對象的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Vue實現(xiàn)按鈕旋轉(zhuǎn)和移動位置的實例代碼
這篇文章主要介紹了Vue實現(xiàn)按鈕旋轉(zhuǎn)和移動位置的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
el-form表單el-form-item驗證規(guī)則里prop一次驗證兩個或多個值問題
這篇文章主要介紹了el-form表單el-form-item驗證規(guī)則里prop一次驗證兩個或多個值問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
vue實現(xiàn)文章內(nèi)容過長點擊閱讀全文功能的實例
下面小編就為大家分享一篇vue實現(xiàn)文章內(nèi)容過長點擊閱讀全文功能的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12

