一、Vuex是什麼
- Vuex是一個大管家,多個組件共享的變量全部存儲在一個對象裡
- 將這個對象放在頂層vue實例中,讓其他組件使用,如下圖為多頁面
二、Vuex的五個屬性
- state:vuex的基本數據,用來儲存變量
- getter:從基本數據(state)派生的數據 ,相當於state的計算屬性(computed)
- mutation:提交更新數據的方法,必須是同步,美國mutation都有一個字符串事件類型(type) 和回調函數(handler)
- action:和mutation的功能大致相同,不同之處在於(action提交的是mutation,不是直接變更狀態;action包含任意異步操作)
- module:模塊化vuex,可以讓每一個模塊擁有自己的state,mutation,action,getters
三、Vuex狀態管理開發
3.1 state & mutations
npm install vuex --save
//store文件夾下 新增index.js
import Vue from 'vue'
import Vuex from 'vuex'//vuex
Vue.use(Vuex)
const store = new Vuex.Store({//Vuex.Store
state: {//管理的状态对象
counter: 1000,
},
mutations: {//只能包含同步的代码, 不能写异步代码
increament(state) {
state.counter ++;
}
}
})
export default store
//在main.js全局註冊
import Store from './components/store/index'
new Vue({
el: '#app',
router: router,
i18n: '',
Store,
components: { App },
template: '<App/>',
})
//在使用的頁面
<button @click="addition">+</button>
<p>{{$store.state.counter}}</p>
computed:{
counter:function(){
return this.$store.state.counter
}
},
methods:{
addition(){
this.$store.commit('increament')
}
}
3.2 getters相當於state的計算屬性(computed)
state: {
student:[
{ id: 111, name: "kk", age:18 },
{ id: 121, name: "kko", age:28 },
{ id: 131, name: "kkoo", age:38 },
{ id: 141, name: "kkpo", age:8 },
]
},
getters: {
more20Stu(state) {
//找出大於18歲的數據
return state.student.filter(s => s.age > 18)
},
}
mutation 只能通過其他方式來更新屬性未定義的內容
//在使用的地方
<p>{{$store.state.info}}</p>
<button @click="addInfo">更新用戶</button>
addInfo(){
this.$store.commit('upInfo')
},
//index.js
info: {
id:151,name:"kkk",age:35
}
upInfo(state) {
Vue.set(state.info,'address','los')
Vue.delete(state.info,'age')
}
3.3 mutation提交更新數據的方法,必須是同步,如下為異步,就無法做到響應式
increament(state) {
setTimeout(()=>{
state.counter++;
},1000)
},
3.4 actions(為了解決異步如上圖頁面顯示和數據不同步的問題,將actions dispatch 給mutation更新)
//index.js
actions: {//異步操作
aUpdateInfo(context,payload) {
setTimeout(() => {
context.commit('upInfo');
payload.success();
payload.message
},1000)
}
}
upInfo(state) {
Vue.set(state.info, 'address', 'los');
}
//在使用地方
<button @click="updateInfo">更用戶</button>
updateInfo(){
this.$store.dispatch('aUpdateInfo',{
message:"message",
success:()=>{
console.log('ok')
}
})
},
3.5 mutation 常量類型
//index.js
mutations: {//只能包含同步的代码, 不能写异步代码
increament(state) {
state.counter ++;
}
}
//mutation-types.js 導出
export const INCREAMENT = 'increament'
//使用地方引用
import {INCREAMENT} from './store/mutation-types'
addition(){
this.$store.commit(INCREAMENT)
},
3.6 module (模塊) vuex 允許我們將store分割成大大小小的對象,每個對象擁有自己的state,getter,action,mutation,這個對象叫module
const moduleA={
state: {count:0 },
getters: { fiveCount(state) {
return state.count + 5
}
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
ifcrementRootSum({state,commit,rootState }) {
if ((state.count - rootState.count) * 2 === 1) {
commit('increment')
}
}
}
}
export default moduleA
//使用的地方引用
import moduleA from './module/moduleA';
export default new Vuex.Store({
modules: {
moduleA
},
// ...
}