vuex狀態管理
概述
- vuex主要由state,mutations,actions,getters四部分構成(modules本文暫不闡述)
- state
- 全域狀態,只讀
- 組件讀取state方式
- 根組件上引入并掛載store物件,其他組件在計算屬性通過$store獲取狀態
- 可以在計算屬性上使用mapState輔助函式簡化state獲取程序
- getters
- 全域狀態的計算屬性
- 組件讀取getters方式,同state
- getters引數
- state(全域狀態)
- getters (全域其他getters)
- 可以通過閉包(回傳一個新函式)進行函式式傳參呼叫
- mutations
- 唯一改變全域狀態的方法,只允許同步修改state
- 組件使用mutations方式
- 使用$store.commit(名字, 引數)
- 可以在組件methods中使用mapMutations輔助函式簡化
- mutations-types(可選)
- 可以使用常量來代替字串,以減少提交mutation的型別的出錯率
- 如:increment -> export const INCREMENT = "increment"
- actions
- 允許異步改變全域狀態的方式
- 本質是在action函式內部手動提交mutation
- 組件使用actions方式
- 使用$store.dispatch(名字, 引數)
- actions引數
- context物件,包含conmmit, dispatch方法,state等
- payload
- 可以在action函式中使用promise來控制異步任務順序
代碼示例
// store
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex);
const store = new Vuex.Store({
// 開發環境下開啟嚴格模式,不是由 mutation 函式改變的,將會拋出錯誤
strict: process.env.NODE_ENV !== "production",
state: {
count: 1,
msg: "我是msg",
},
mutations: {
// 同步改變count
increment(state, payload) {
state.count += payload;
},
setMsg(state, payload) {
state.msg = payload;
},
},
actions: {
// 異步改變count
incrementAsync({ commit }, payload) {
return new Promise((resolve) => {
setTimeout(() => {
commit("increment", payload);
resolve("ODK");
}, 2000);
});
},
},
getters: {
// count的計算屬性,可以使用其他getters
countAddHundred({ count }, { countSubHundred }) {
return count + countSubHundred * 10 + 100;
},
countSubHundred(state) {
return state.count - 100;
},
// getters傳參
countmutiNum({ count }) {
return (num) => count * num;
},
},
});
export default store;
// 組件
<template>
<div>
<input v-model="message" />
<p>{{ msg }}</p>
<button @click="btnClick">點擊+10</button>
<p>{{ count }}</p>
<!-- getters傳參 -->
<p>{{ countmutiNum(6) }}</p>
</div>
</template>
<script>
// 使用輔助函式,避免每次從$store匯出
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
methods: {
...mapMutations(["increment", "setMsg"]),
...mapActions(["incrementAsync"]),
async btnClick() {
// 分發一個異步action,回傳的是一個promise
const result = await this.incrementAsync(10);
console.log(result);
},
},
computed: {
...mapState(["count", "msg"]),
...mapGetters(["countAddHundred", "countSubHundred", "countmutiNum"]),
// 使用v-model雙向系結vuex的資料,需要重寫set方法
message: {
get() {
return this.msg;
},
set(value) {
this.setMsg(value);
},
},
},
};
</script>
關系圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/500838.html
標籤:其他
上一篇:自定義SvgIcon公用組件
