Vuex 的 action 屬性?xún)?nèi),可以定義異步操作邏輯,以滿(mǎn)足某些業(yè)務(wù)場(chǎng)景要求。在組件內(nèi),是通過(guò) $store.dispatch 來(lái)觸發(fā) action 定義的函數(shù)。
我們使用 action,來(lái)為計(jì)數(shù)器異步增 1。
1 Promise 方式
main.js:
const store = new Vuex.Store({ state: { count: 0, }, mutations: { increment(state, n = 1) { state.count += n; } }, actions: { asyncInrement(context) { return new Promise(resolve => { setTimeout(() => { context.commit('increment'); resolve(); }, 1000) }); } } });
這里使用了 Promise ,在 1 s 后提交了 mutations 中定義的 increment 遞增函數(shù)。它是 ES6 語(yǔ)法,有三種狀態(tài):
狀態(tài) | 說(shuō)明 |
---|---|
Pending | 進(jìn)行中 |
Resolved | 已完成 |
Rejected | 失敗 |
index.vue:
<template> <div> {{count}} <button @click="asyncIncrementByAction">+1</button> </div> </template> <script> export default { name: "index.vue", computed: { count() { return this.$store.state.count; } }, methods: { asyncIncrementByAction() { this.$store.dispatch('asyncInrement').then(() => { console.log(this.$store.state.count); }) } } } </script>
2 Callback 方式
也可以使用普通回調(diào)來(lái)實(shí)現(xiàn)異步方案。
main.js
const store = new Vuex.Store({ ... actions: { ... asyncInrement2(context, callback) { setTimeout(() => { context.commit('increment'); callback(); }, 1000); } } });
index.vue:
<template> <div> ... {{count}} <button @click="asyncIncrementByAction2">+1(Callback)</button> </div> </template> <script> export default { ... methods: { ... asyncIncrementByAction2() { this.$store.dispatch('asyncInrement2',() => { console.log(this.$store.state.count); }); } } } </script>
3 效果
vuex action和mutations的區(qū)別
action的功能和mutation是類(lèi)似的,都是去變更store里的state,不過(guò)action和mutation有兩點(diǎn)不同:
1、action主要處理的是異步的操作,mutation必須同步執(zhí)行,而action就不受這樣的,也就是說(shuō)action中我們既可以處理同步,也可以處理異步的操作
2、action改變狀態(tài),最后是通過(guò)提交mutation
使用方式:
安裝:
npm install vuex --save
引用:
store.js
方法一:
/** * 創(chuàng)建完文件后需要去到main.js中引入成全局 */ import Vue from "vue"; import Vuex from "vuex"; //使用vuex Vue.use(Vuex); const state = { targetUser: {} //用戶(hù)詳細(xì)資料數(shù)據(jù) }; const getters = { //獲取到用戶(hù)狀態(tài),//實(shí)時(shí)監(jiān)聽(tīng)state值的變化(最新?tīng)顟B(tài)) targetUser: state => state.targetUser }; const mutations = { //自定義改變state初始值的方法 SET_TARGET_USER(state, targetUser) { if (targetUser) { state.targetUser = targetUser; //如果targetUser有內(nèi)容就賦給狀態(tài)信息 } else { //如果沒(méi)內(nèi)容就給targetUser賦空對(duì)象 state.targetUser = {}; } } }; const actions = { //這里面的方法是用來(lái)異步觸發(fā)mutations里面的方法,context與store 實(shí)例具有相同方法和屬性 // 頁(yè)面定義的setGargetUser,targetUser為頁(yè)面?zhèn)鬟^(guò)來(lái)的值 setGargetUser({ commit }, targetUser) { commit("SET_TARGET_USER", targetUser); } };
存儲(chǔ)頁(yè)面:
this.$store.dispatch('setGargetUser',friend)
獲取頁(yè)面:
computed:{ // 提示vuex中存入的用戶(hù)詳細(xì)資料 targetUser(){ return this.$store.getters.targetUser } },
以上方法有一個(gè)問(wèn)題就是如果多人開(kāi)發(fā);會(huì)出現(xiàn)不利于管理,下面用一個(gè)方法定義一個(gè)常量
存儲(chǔ):
this.$store.dispatch('setUser',decode)
store.js
/** * 創(chuàng)建完文件后需要去到main.js中引入成全局 */ import Vue from "vue"; import Vuex from "vuex"; // 持久存儲(chǔ)插件 import createPersistedState from "vuex-persistedstate"; //使用vuex Vue.use(Vuex); /** * 在需要多人協(xié)作的項(xiàng)目中,我們可以使用常量代替mutation 事件類(lèi)型。這在各種 Flux 實(shí)現(xiàn)中是很常見(jiàn)的模式。同時(shí)把這些常量放在單獨(dú)的文件中可以讓協(xié)作開(kāi)發(fā)變得清晰。 * 定義存儲(chǔ)信息 * * */ const types = { SET_TARGET_USER: "SET_TARGET_USER" //詳細(xì)資料 }; const state = { //用戶(hù)初始化的狀態(tài) targetUser: {} //用戶(hù)詳細(xì)資料數(shù)據(jù) }; const getters = { //獲取到用戶(hù)狀態(tài),//實(shí)時(shí)監(jiān)聽(tīng)state值的變化(最新?tīng)顟B(tài)) targetUser: state => state.targetUser }; const mutations = { //自定義改變state初始值的方法 [types.SET_TARGET_USER](state, targetUser) { if (targetUser) { state.targetUser = targetUser; //如果targetUser有內(nèi)容就賦給狀態(tài)信息 } else { //如果沒(méi)內(nèi)容就給targetUser賦空對(duì)象 state.targetUser = {}; } } }; const actions = { //這里面的方法是用來(lái)異步觸發(fā)mutations里面的方法,context與store 實(shí)例具有相同方法和屬性 setGargetUser({ commit }, targetUser) { commit(types.SET_TARGET_USER, targetUser); // localStorage.setItem("SET_TARGET_USER", JSON.stringify(targetUser)); } }; export default new Vuex.Store({ state, mutations, getters, actions, });
取值:
this.$store.getters.targetUser
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com