Vuex總體案例詳解

一、簡介
我們來看看對 Vuex 比較專業(yè)的介紹:
Vuex 是一個專為 Vue 開發(fā)的應(yīng)用程序的狀態(tài)管理模式,它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。
簡而言之,Vuex 采用類似全局對象的形式來管理所有組件的公用數(shù)據(jù),如果想修改這個全局對象的數(shù)據(jù),得按照Vuex提供的方式來修改(不能自己隨意用自己的方式來修改)。
二、優(yōu)點
Vuex狀態(tài)管理跟使用傳統(tǒng)全局變量的不同之處:
- Vuex的狀態(tài)存儲是響應(yīng)式的: 就是當(dāng)你的組件使用到了這個 Vuex 的狀態(tài),一旦它改變了,所有關(guān)聯(lián)的組件都會自動更新相對應(yīng)的數(shù)據(jù),這樣開發(fā)者省事很多。
- 不能直接修改Vuex的狀態(tài): 如果是個全局對象變量,要修改很容易,但是在 Vuex 中不能這樣做,想修改就得使用 Vuex 提供的唯一途徑:顯示地提交(
commint)mutations來實現(xiàn)修改。這樣做的好處就是方便我們跟蹤每一個狀態(tài)的變化,在開發(fā)過程中調(diào)試的時候,非常實用。
三、使用步驟
1. 安裝Vuex
npm install vuex --save
2. 引用Vuex
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
3. 創(chuàng)建倉庫Store
要使用 Vuex,我們要創(chuàng)建一個實例 store,我們稱之為倉庫,利用這個倉庫 store 來對我們的狀態(tài)進行管理。
//創(chuàng)建一個 store
const store = new Vuex.Store({});
四、包含模塊
- State:定義了應(yīng)用狀態(tài)的數(shù)據(jù)結(jié)構(gòu),可以在這里設(shè)置默認的初始狀態(tài)。
- Getter:允許組件從 store 中獲取數(shù)據(jù),
mapGetters輔助函數(shù)僅僅是將 store 中的getter映射到局部計算屬性。 - Mutation:是唯一更改 store 中狀態(tài)的方法,且必須是同步函數(shù)。
- Action:用于提交
mutation,而不是直接變更狀態(tài),可以包含任意異步操作。 - Module:可以將 store 分割成模塊(module)。每個模塊擁有自己的
state、mutation、action、getter、甚至是嵌套子模塊
Vuex的作用類似全局對象,Vuex 使用單一狀態(tài)樹,用一個對象State包含了整個應(yīng)用層級的所有狀態(tài),你可以理解為這些狀態(tài)就是一堆全局變量和數(shù)據(jù)。

1. State
假設(shè)我們有一個全局狀態(tài) count 的值為 5。那么,我們就可以將其定義為 state 對象中的 key 和 value,作為全局狀態(tài)供我們使用。如下:
//創(chuàng)建一個 store
const store = new Vuex.Store({
//state存儲應(yīng)用層的狀態(tài)
state:{
count:5 //總數(shù):5
}
});
2. Getters
可以認為,getters 是store的計算屬性,類似于computed,對state里的數(shù)據(jù)進行一些過濾,改造等等
假設(shè)我們要在state.count的基礎(chǔ)上派生出一個新的狀態(tài)newCount出來,就適合使用我們的 getters
getters 接受 state 作為其第一個參數(shù)
const store = new Vuex.Store({
//state存儲應(yīng)用層的狀態(tài)
state:{
count:5 //總數(shù):5
},
getters:{
newCount:state => state.count * 3
}
});
在組件中獲取 {{newCount}} 方式:
export default {
computed: {
newCount(){
return this.$store.getters.newCount;
}
}
};
3. Mutations
Vuex 給我們提供修改倉庫 store中的狀態(tài)的唯一辦法就是通過提交mutation ,且必須是同步函數(shù)
我們在 mutations中定義了一個叫increment的函數(shù),函數(shù)體就是我們要進行更改的地方
會接受 state作為第一個參數(shù),第二個是自定義傳參
const store = new Vuex.Store({
//state存儲應(yīng)用層的狀態(tài)
state:{
count:5 //總數(shù):5
},
// mutations是修改state中數(shù)據(jù)的唯一途徑
mutations:{
increment(state,value){
state.count += value;
}
}
});
我們在提交commit時候,第一個參數(shù)"increment",就是對應(yīng)在 mutations中的increment方法,第二個參數(shù)是自定義值。例如:
methods: {
getVal(event) {
//獲取當(dāng)前的按鍵的值
let value = event.target.dataset.value;
//通過commit提交一個名為increment的mutation
this.$store.commit("increment", value);
}
}
在組件中獲取 {{count}} 方式:
export default {
computed: {
count(){
return this.$store.state.count;
}
}
};
4. Action
- 用于提交
mutation,而不是直接變更狀態(tài),可以包含任意異步操作 - 只有通過
action=>mutations=>states,這個流程進行操作,具體步驟如下:
export default new Vuex.Store({
//存放數(shù)據(jù)
state: {
obj: {},
},
//4. 通過commit mutations中的方法來處理
mutations: {
getParam(state, Object) {
//5.修改state中的數(shù)據(jù)
state.obj = Object
}
},
//2.接受dispatch傳遞過來的方法和參數(shù)
actions: {
getParamSync(store, Object) {
// 處理異步操作
setTimeout(() => {
//3.通過commit提交一個名為getParam的mutation
//action 函數(shù)接收一個 store 的實例對象,因此你可以調(diào)用 store.commit 提交一個 mutation
store.commit('getParam', Object);
}, 1000)
}
}
})
然后我們就在組件里這么調(diào)用就可以了
methods: {
getVal() {
let name= 'xia';
let age= '26';
let sex= 'man';
//1.通過dispatch將方法getParamSync和多個參數(shù){name,age,sex}傳遞給actions
this.$store.dispatch('getParamSync',{name,age,sex})
}
}
5. Modules
隨著項目的復(fù)雜度增大,為了方便管理 Vuex,一般會將其按功能分割成不同的模塊(Module),方便日后管理。每個模塊擁有自己的 state、mutation、action、getter 甚至是嵌套子模塊
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import * as getters from './getters'
import moduleA from './module/moduleA' // 模塊A
import moduleB from './module/moduleB' // 模塊B
Vue.use(Vuex)
export default new Vuex.Store({
actions,
getters,
state,
mutations,
modules: {
moduleA,
moduleB
}
})
moduleA.js / moduleB.js 文件
// 每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊
export default {
state: {
text: 'moduleA'
},
getters: {},
mutations: {},
actions: {}
}
然后我們就在組件里這么調(diào)用就可以了
<template>
<div class="demo">
<h1>{{getText1}}</h1>
<h1>{{getText2}}</h1>
</div>
</template>
computed: {
getText1(){
return this.$store.state.moduleA.text;
},
//或
...mapState({
getText2: state => state.moduleB.text;
})
}
由此可知,模塊內(nèi)部的 state 是局部的,只屬于模塊本身所有,所以外部必須通過對應(yīng)的模塊名進行訪問。
五、Vuex最最簡單的項目實例
運用vuex語法糖mapMutations和mapGetters
1. 存儲數(shù)據(jù)
a.vue 文件
import { mapMutations } from "vuex"; // 引入mapMutations
export default {
methods: {
...mapMutations({
// 將changeNews與mutations中的SET_NEWS關(guān)聯(lián)
changeNews: "SET_NEWS"
}),
submit(){
// 提交一個名為changeNews的mutation,并傳入?yún)?shù)val
let val = 'test news';
this.changeNews(val);// 相當(dāng)于this.$store.commit("changeNews", val);
}
}
}
2. 獲取數(shù)據(jù)
b.vue 文件
import { mapGetters } from "vuex"; // 引入mapGetters
export default {
computed: {
// 用vuex讀取數(shù)據(jù)(讀取的是getters.js中的數(shù)據(jù))
// 相當(dāng)于this.$store.getters.news(vuex語法糖)
...mapGetters(["news"])
},
created() {
// 獲取getters中news數(shù)據(jù)
console.log(this.news);
}
}
3. store文件目錄結(jié)構(gòu)

index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import * as getters from './getters'
//每次修改state都會在控制臺打印log
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug, // 當(dāng)debug=true時開啟嚴(yán)格模式(性能有損耗)
plugins: debug ? [createLogger()] : []
})
state.js
const state = {
news: {}
}
export default state;
mutations.js
const mutations = {
SET_NEWS(state, val) {
state.news= val
}
}
export default mutations;
actions.js
//異步處理
const actions = {
M_NEWS({ commit }, val) {
commit('SET_NEWS', val); // commit mutations修改
}
}
export default actions;
getters.js
// 通常通過getters取數(shù)據(jù) (this.$store.getters.news;) export const news = state => state.news // 不做其他處理 直接映射出去
4. 使用store
在 main.js 中引用
import store from './store' //vuex存儲文件
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
到此這篇關(guān)于Vuex總體案例詳解的文章就介紹到這了,更多相關(guān)Vuex總體內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在vue.js渲染完界面之后如何再調(diào)用函數(shù)
這篇文章主要介紹了在vue.js渲染完界面之后如何再調(diào)用函數(shù)的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
前端vue實現(xiàn)的h5頁面接入微信支付流程(jsapi方式)
vue實現(xiàn)微信支付有三種方式,第一種方式是PC端支付,第二種方式是H5支付,第三種方式是微信公眾號支付,這篇文章主要給大家介紹了關(guān)于前端vue實現(xiàn)的h5頁面接入微信支付流程,文中介紹的方法是利用jsapi方式,通過代碼將實現(xiàn)的方法介紹的非常詳細,需要的朋友可以參考下2024-01-01
關(guān)于vue-resource報錯450的解決方案
本篇文章主要介紹關(guān)于vue-resource報錯450的解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07

