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使用keep-alive實現(xiàn)組件切換時保存原組件數(shù)據(jù)方法
這篇文章主要介紹了vue使用keep-alive實現(xiàn)組件切換時保存原組件數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
vue3集成Element-plus實現(xiàn)按需自動引入組件的方法總結(jié)
vue3出來一段時間了,element也更新了版本去兼容vue3,下面這篇文章主要給大家介紹了關(guān)于vue3集成Element-plus實現(xiàn)按需自動引入組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07
基于Vue.js的文件選擇與多選對話框組件Dccfile的使用教程
在現(xiàn)代前端開發(fā)中,Vue.js 提供了強大的組件化開發(fā)能力,使得我們可以輕松構(gòu)建復(fù)雜且可復(fù)用的用戶界面,本文將介紹一個基于 Vue.js 的文件選擇與多選對話框組件——Dccfile,并詳細解析其功能和實現(xiàn)細節(jié)2025-04-04
Vue CLI3中使用compass normalize的方法
這篇文章主要介紹了Vue CLI3中使用compass normalize的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
Vue通過字符串關(guān)鍵字符實現(xiàn)動態(tài)渲染input輸入框
這篇文章主要為大家詳細介紹了Vue如何通過字符串關(guān)鍵字符實現(xiàn)動態(tài)渲染input輸入框。文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-12-12

