1. 創建一個uniapp項目
2. 在項目目錄下用npm安裝 vuex
npm install vuex --save
3. 在項目根目錄下創建 store文件夾,在store文件夾中創建 index.js

4. 在index.js中顯式地通過 Vue.use() 來安裝 Vuex:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
5.在index.js中創建store
5.1 完整的store目錄如下:
const store = new Vuex.Store({
state: {
// 存放狀態
},
getters: {
// state的計算屬性
},
mutations: {
// 更改state中狀態的邏輯,同步操作
},
actions: {
// 提交mutation,異步操作
},
// 如果將store分成一個個的模塊的話,則需要用到modules。
//然后在每一個module中寫state, getters, mutations, actions等。
modules: {
a: moduleA,
b: moduleB,
// ...
}
});
5.2 導出store
export default store
6. 在main.js 中引入store

vuex的基礎用法
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 存放狀態
count:0,
test:'這是store.js中的數據'
},
getters: {
// state的計算屬性
//用 this.$store.getters.getData()讀取
getData(state){
return state;
}
},
mutations: {
// 更改state中狀態的邏輯,同步操作
//用 this.$store.commit('function_name',payload) 使用,若無參數則不寫payload
add(state,n){
state.count += n;
}
},
actions: {
// 提交mutation,異步操作
}
})
export default store

