vuex中store存儲store.commit和store.dispatch的區(qū)別及說明
store存儲store.commit和store.dispatch區(qū)別
代碼示例:
this.$store.commit('loginStatus', 1); this.$store.dispatch('isLogin', true);
規(guī)范的使用方式:
// 以載荷形式 store.commit('increment',{ ? amount: 10 ? //這是額外的參數(shù) }) // 或者使用對象風格的提交方式 store.commit({ ? type: 'increment', ? amount: 10 ? //這是額外的參數(shù) })
主要區(qū)別
dispatch
:含有異步操作,數(shù)據(jù)提交至 actions ,可用于向后臺提交數(shù)據(jù)
寫法示例: this.$store.dispatch('isLogin', true);
commit
:同步操作,數(shù)據(jù)提交至 mutations ,可用于登錄成功后讀取用戶信息寫到緩存里
寫法示例: this.$store.commit('loginStatus', 1);
兩者都可以以載荷形式或者對象風格的方式進行提交
vuex store原理及使用指南
Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化。
Vuex的store組件,主要存儲應(yīng)用中的狀態(tài),具體應(yīng)用中如何來用呢?存儲我們也可以使用緩存比如uni.setStorageSync(...) uni.getStorageSync(),來存儲應(yīng)用級的狀態(tài),也可以實現(xiàn)相應(yīng)需求。單純緩存數(shù)據(jù)可能并不能很好滿足一定的業(yè)務(wù)場景,而且緩存數(shù)據(jù)是多樣化的,狀態(tài)的交互在應(yīng)用中存在很多,不同模塊間互相通過狀態(tài)調(diào)用來通信,而如果僅通過緩存值來通信,如果需求改動,可能造成比較大的修改維護量。Store組件是封裝比較好的對象來管理統(tǒng)一狀態(tài)及數(shù)據(jù)的,這樣可能更優(yōu)雅,容易維護一些,比如:他的state對象存放狀態(tài)屬性及值,用getters中定義訪問屬性數(shù)據(jù)的方法,mutations中定義修改屬性的同步方法,actions中定義外部訪問屬性數(shù)據(jù)的異步方法。
使用
我們通過如下內(nèi)容,從安裝、到一個實例場景的實現(xiàn),使用vue框架來實現(xiàn)這個場景,來說明vuex的store的使用。
安裝
$ npm install vuex --save
注意此處可能會報錯,最好指定vuex版本,用如下命令
$ npm install vuex@3.6.2 --save
示例需求場景
應(yīng)用在登錄后存儲狀態(tài)數(shù)據(jù):1.是否登錄is_login(true已登錄,false未登錄);2.當前用戶id curr_uid。
源碼目錄結(jié)構(gòu)
本源碼使用vue2+uview2.x ui
store組件初始化
main.js,引入store組件
import App from './App' import store from "./store"; ... const app = new Vue({ store, ...App }) app.$mount() ...
App.vue,狀態(tài)緩存處理,避免刷新時狀態(tài)被清空
export default { ... created(){ //在頁面刷新時將vuex里的信息保存到localStorage里 https://blog.csdn.net/XinYe666666/article/details/102939381 window.addEventListener("beforeunload",()=>{ localStorage.setItem("messageStore",JSON.stringify(this.$store.state)) }) //在頁面加載時讀取localStorage里的狀態(tài)信息 localStorage.getItem("messageStore") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("messageStore")))); }, ...
store,存儲狀態(tài)的組件文件,加入模塊化
index.js,存儲組件的入口文件,加載狀態(tài)組件、模塊化
import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' Vue.use(Vuex) const store = new Vuex.Store({ modules: { user }, });
user.js 模塊狀態(tài)組件
import { getToken,removeToken } from '@/common/auth.js'; const state={ //要設(shè)置的全局訪問的state對象 is_login: false, curr_uid:0 //要設(shè)置的初始屬性值 }; const getters = { //實時監(jiān)聽state值的變化(最新狀態(tài)) isLogin(state) { //承載變化的showFooter的值 return state.is_login }, getCurrUid(state){ //承載變化的curr_uid的值 return state.curr_uid } }; const mutations = { setLogin(state) { //自定義改變state初始值的方法,這里面的參數(shù)除了state之外還可以再傳額外的參數(shù)(變量或?qū)ο?; state.is_login = true; }, setLogout(state) { //同上 state.is_login = false; removeToken(); }, setCurrUid(state,uid){ //同上,這里面的參數(shù)除了state之外還傳了需要增加的值sum state.curr_uid=uid; } }; const actions = { setLogin(context) { //自定義觸發(fā)mutations里函數(shù)的方法,context與store 實例具有相同方法和屬性 context.commit('setLogin'); }, setLogout(context) { //同上注釋 context.commit('setLogout'); }, setCurrUid(context,uid){ //同上注釋,uid為要變化的形參 context.commit('setCurrUid',uid) } }; export default { namespaced: true, //用于在全局引用此文里的方法時標識這一個的文件名 state, getters, mutations, actions }
這里引入了token緩存的清除處理功能是額外的,先看基本功能實現(xiàn)了登錄狀態(tài)的設(shè)置讀寫,當前uid設(shè)置讀寫,公開的讀寫的相應(yīng)調(diào)用方法。
login.vue ,我們在登錄頁面調(diào)用生成狀態(tài)數(shù)據(jù)的寫入
import { setToken } from 'common/auth.js'; import { mapActions} from 'vuex'; export default { .... methods: { ...mapActions('user', ['setLogin','setCurrUid']), submit() { const _self = this; ... postLogin({ username:v_username,password:v_password }).then(res => { if(res.code==0){ uni.$u.toast('登錄成功'); _self.$store.dispatch("user/setLogin"); _self.$store.dispatch("user/setCurrUid",res.data.uid); ...
這里我們把關(guān)鍵調(diào)用代碼寫出,這里是調(diào)用狀態(tài)模塊user的寫入方法進行登錄狀態(tài)、用戶uid的寫入。
user.vue 我們這里讀取登錄狀態(tài),用戶uid信息
import { mapGetters} from 'vuex'; export default { ... computed:{ ...mapGetters('user',{ //用mapGetters來獲取user.js里面的getters isLogin:'isLogin', currUid:'getCurrUid' }) }, onLoad() { this.initData(); }, methods: { initData() { console.log("initData.store=",this.$store); console.log('init.isLogin=',this.isLogin); console.log('init.currUid=',this.currUid); ...
這里我們通過vue的computed方法注入從store組件的mapGetters設(shè)置的狀態(tài)數(shù)據(jù)。后續(xù)代碼就可以從這里讀取狀態(tài)數(shù)據(jù)了。
我們打印store對象結(jié)構(gòu),幫助理解store對象的存儲結(jié)構(gòu)
我們看到store對象的存儲結(jié)構(gòu),就是一個對象,封裝的屬性方法,和我們定義的js文件中某些方法、屬性相對應(yīng)。我們按照它的語法結(jié)構(gòu)來訪問就可以了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue項目中將element-ui table表格寫成組件的實現(xiàn)代碼
這篇文章主要介紹了vue項目中將element-ui table表格寫成組件的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-06-06Vue使用mounted和created時,this無法指向data中的數(shù)據(jù)問題
這篇文章主要介紹了Vue使用mounted和created時,this無法指向data中的數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07vue-video-player 解決微信自動全屏播放問題(橫豎屏導致樣式錯亂問題)
這篇文章主要介紹了vue-video-player 解決微信自動全屏播放問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02