一、初始化Vuex
Vuex是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化削罩。
如果一份數(shù)據(jù)需要在多個組件中使用,組件間傳值又比較復雜,就可以使用vuex托管數(shù)據(jù)荆永。
1、安裝Vuex
npm install vuex --save
2国章、導入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3具钥、創(chuàng)建狀態(tài)管理對象 store
state選項:定義狀態(tài)(狀態(tài)就是數(shù)據(jù))。
mutations選項:定義修改狀態(tài)的方法(注意:這里面只能定義同步方法)液兽。
export default new Vuex.Store({
// 定義全局狀態(tài)(狀態(tài)就是數(shù)據(jù))
state:{
car:{
name:'奔馳',
price:'40W'
}
},
// 定義修改狀態(tài)的方法
mutations:{
//該方法骂删,修改汽車信息
updateCar(state,val){
state.car = val
}
}
})
4掌动、注冊給Vue
// 導入當前項目中的全局狀態(tài)管理對象
import store from './store'
new Vue({
// 在vue實例中使用全局狀態(tài)管理對象
store,
render: h => h(App)
}).$mount('#app')
5、簡單使用
$store:返回的是當前項目中的全局狀態(tài)對象宁玫。
commit()方法:用于執(zhí)行指定的mutations里面的方法粗恢。
(1)獲取數(shù)據(jù)
在組件中,直接通過$store.state就可以獲取到全局狀態(tài)對象管理的狀態(tài)數(shù)據(jù)欧瘪,直接渲染到頁面眷射。
<div>車輛名稱:{{ $store.state.car.name }}</div>
<div>車輛價格:{{ $store.state.car.price }}</div>
(2)修改數(shù)據(jù)
<div>車輛名稱:{{ $store.state.car.name }}</div>
<div>車輛價格:{{ $store.state.car.price }}</div>
<button @click="updateCar">修改汽車信息</button>
二、核心概念
1佛掖、state
state選項:定義狀態(tài)(狀態(tài)就是數(shù)據(jù))
state: {
name:'張三'
}
通過$store.state.數(shù)據(jù)名使用妖碉。
<div>姓名:{{ $store.state.name }}</div>
2、getters
getters選項:定義計算屬性芥被。方法的參數(shù)是狀態(tài)對象欧宜。
getters:{
// 方法的第一個參數(shù)是全局狀態(tài)
nameInfo(state){
return `我的名字叫${state.name}`
}
}
通過$store.getters.屬性名使用計算屬性。
<div>{{ $store.getters.nameInfo }}</div>
3拴魄、mutations
mutations選項:定義修改狀態(tài)的方法(注意:這里的方法一般都是同步方法)冗茸。方法的第一個參數(shù)是狀態(tài)對象,第二個參數(shù)是新值羹铅。
mutations:{
// 修改姓名
updateName(state,val){
state.name = val
}
},
通過commit()方法蚀狰,調(diào)用mutations里面的方法。
this.$store.commit("updateName", '李四');
4职员、actions
actions選項:定義操作狀態(tài)的方法(這里的方法可以定義異步方法)麻蹋。
注意:actions里的方法最好不要直接操作state狀態(tài),而是通過調(diào)用mutations里面的方法去修改狀態(tài)焊切。所以扮授,actions直接操作的是mutations。
state: {
carAddress:'意大利'
},
mutations:{
//修改汽車的產(chǎn)地
updateCarAddress(state,val){
state.carAddress = val
}
},
actions:{
//修改汽車的產(chǎn)地
//方法的第一個參數(shù)是全局狀態(tài)管理對象专肪,第二個參數(shù)是具體的值
updateCarAddress(store,val){
axios.get(val).then(({data})=>{
// 方式一:這里可以直接修改狀態(tài)
// store.state.carAddress = data.address
// 方式二:通過調(diào)用mutations里面的方法修改狀態(tài)
store.commit('updateCarAddress',data.address)
})
}
}
通過dispatch()方法刹勃,調(diào)用actions里面定義的方法。
this.$store.dispatch('updateCarAddress','data/address.json')
5嚎尤、modules
由于使用單一狀態(tài)樹荔仁,應(yīng)用的所有狀態(tài)會集中到一個比較大的對象。當應(yīng)用變得非常復雜時芽死,store 對象就有可能變得相當臃腫乏梁。
為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)关贵。每個模塊擁有自己的 state遇骑、mutation、action揖曾、getter落萎、甚至是嵌套子模塊亥啦。
(1)定義模塊
namespaced屬性:默認情況下,action练链、mutation 和 getter 是注冊在全局命名空間的翔脱。通過設(shè)置namespaced屬性為true,將action兑宇、mutation 和 getter全部注冊到私有命名空間中碍侦。
export default {
namespaced:true,
// 狀態(tài)
state:{
planeName:'空客404',
planePrice:'10Y',
planeAddress:'中國'
},
// 計算屬性
getters:{
planeInfo(state){
return `飛機名稱:${state.planeName},飛機價格:${state.planePrice}隶糕,飛機產(chǎn)地:${state.planeAddress}`
}
},
// 同步方法
mutations:{
updatePlaneName(state,val){
state.planeName = val
},
updatePlanePrice(state,val){
state.planePrice = val
}
},
// 異步方法
actions:{
updatePlanePrice(store,val){
setTimeout(() => {
store.commit('updatePlanePrice',val)
}, 500);
}
}
}
(2)在全局狀態(tài)管理對象中導入模塊
// 導入飛機模塊
import plane from './modules/plane.js'
// 創(chuàng)建一個全局狀態(tài)管理對象并導出
export default new Vuex.Store({
// 模塊
modules:{
// 飛機模塊
plane
}
})
(3)使用模塊
① 獲取模塊中的state狀態(tài)
要從私有模塊中獲取數(shù)據(jù)瓷产,方式是:$store.state.模塊名稱.模塊的數(shù)據(jù) 。
<div>飛機名稱:{{ planeName }}</div>
planeName() {
return this.$store.state.plane.planeName;
}
② 獲取模塊中的getters計算屬性
要從私有模塊中獲取計算屬性枚驻,方式是:$store.getters['模塊名/計算屬性']濒旦。
<div>{{planeInfo}}</div>
planeInfo(){
return this.$store.getters['plane/planeInfo']
}
③ 調(diào)用模塊中的mutations定義的方法
調(diào)用私有模塊里面的mutations定義的方法,方式是:$store.commit('模塊名/方法名',新值)再登。
<button @click="updatePlaneName">修改飛機名稱</button>
updatePlaneName(){
this.$store.commit('plane/updatePlaneName','波音747')
}
④ 調(diào)用模塊中的actions定義的方法
調(diào)用私有模塊里面的actions定義的方法尔邓,方式是:$store.dispatch('模塊名/方法名',新值)。
<button @click="updatePlanePrice">修改飛機價格</button>
三锉矢、Vuex使用
1梯嗽、計算屬性中轉(zhuǎn)
直接在模板中使用全局狀態(tài)管理數(shù)據(jù),表達式會寫的很長沽损。所以可以使用計算屬性灯节。
// getters選項定義計算屬性
getters:{
carInfo(state){
return `汽車名稱:${state.carName},汽車價格:${state.carPrice}绵估,汽車產(chǎn)地:${state.carAddress}`
}
}
<!-- 直接在模板中使用全局狀態(tài)里面的計算屬性 -->
<div>{{$store.getters.carInfo}}</div>
<div>{{carInfo}}</div>
//計算屬性
computed:{
// 汽車信息
carInfo(){
// 返回全局狀態(tài)管理里面的計算屬性
return this.$store.getters.carInfo
}
}
2炎疆、映射函數(shù)
通過映射函數(shù)mapState、mapGetters国裳、mapActions形入、mapMutations,可以將vuex.store中的屬性映射到vue實例身上缝左,這樣在vue實例中就能訪問vuex.store中的屬性了亿遂,便于操作vuex.store。
(1)導入映射函數(shù)
// 從vuex中渺杉,導入映射函數(shù)
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
(2)使用映射函數(shù)生成計算屬性
如果vuex里面state的數(shù)據(jù)名稱 跟 頁面中的計算屬性名稱相同蛇数,就可以使用mapState映射函數(shù),自動生成頁面中的計算屬性少办。
如果vuex里面getters的數(shù)據(jù)名稱 跟 頁面中的計算屬性名稱相同苞慢,就可以使用mapGetters映射函數(shù)诵原,自動生成頁面中的計算屬性英妓。
注意:如果要映射模塊里面的state/getters挽放,函數(shù)的第一個參數(shù)設(shè)置為模塊的名稱
<div>汽車名稱:{{ carName }}</div>
<div>汽車價格:{{ carPrice }}</div>
<div>汽車產(chǎn)地:{{ carAddress }}</div>
<div>{{ carInfo }}</div>
<hr/>
<div>飛機名稱:{{ planeName }}</div>
<div>飛機價格:{{ planePrice }}</div>
<div>飛機產(chǎn)地:{{ planeAddress }}</div>
<div>{{ planeInfo }}</div>
computed: {
// mapState映射state
...mapState(["carName", "carPrice", "carAddress"]),
// mapGetters映射getters
...mapGetters(["carInfo"]),
// 映射私有模塊里面的數(shù)據(jù)
...mapState('plane',['planeName','planePrice','planeAddress']),
...mapGetters('plane',['planeInfo'])
}
(3)使用映射函數(shù)生成方法
如果定義的方法名跟全局管理對象中mutations里面的方法名相同,并且定義的方法會帶有一個參數(shù)蔓纠,通過參數(shù)傳遞數(shù)據(jù)辑畦。滿足該規(guī)則,就可以使用mapMutations映射函數(shù)生成方法腿倚。
如果定義的方法名跟全局管理對象中actions里面的方法名相同纯出,并且定義的方法會帶有一個參數(shù),通過參數(shù)傳遞數(shù)據(jù)敷燎。滿足該規(guī)則暂筝,就可以使用mapActions映射函數(shù)生成方法。
注意:如果要映射私有模塊中mutations/actions里面的方法硬贯,函數(shù)的第一個參數(shù)設(shè)置為模塊的名稱焕襟。
<button @click="updateCarName('賓利')">修改汽車名稱</button>
<button @click="updateCarPrice('300W')">修改汽車價格</button>
<button @click="updateCarAddress('data/address.json')">修改汽車產(chǎn)地</button>
<hr/>
<button @click="updatePlaneName('波音747')">修改飛機名稱</button>
<button @click="updatePlanePrice('20Y')">修改飛機價格</button>
methods: {
// 映射全局管理對象中mutations里面的方法
...mapMutations(["updateCarName", "updateCarPrice"]),
// 映射全局管理對象中actions里面的方法
...mapActions(["updateCarAddress"]),
// 映射私有模塊里面的方法
...mapMutations('plane',['updatePlaneName']),
...mapActions('plane',['updatePlanePrice'])
}
3、購物車模塊
import axios from "axios";
export default {
namespaced: true,
state: {
//商品數(shù)組
goodses: [],
},
getters: {
//總價
totalPrice(state) {
return state.goodses.filter((r) => r.ck).map((r) => r.price * r.count).reduce((a, b) => a + b, 0);
},
// 是否全選
isCkAll(state) {
return state.goodses.length>0 & state.goodses.every((r) => r.ck);
},
},
mutations: {
// 加載數(shù)據(jù)的同步方法
loadGoodses(state, val) {
state.goodses = val;
},
// 設(shè)置所有商品的狀態(tài)
ckAll(state, val) {
state.goodses.forEach((r) => {
r.ck = val;
});
},
// 根據(jù)id刪除商品
delGoodsById(state, id) {
let index = state.goodses.findIndex((r) => r.id == id);
state.goodses.splice(index, 1);
},
},
actions: {
// 加載數(shù)據(jù)的異步方法
loadGoodses(store, val) {
axios.get(val).then(({ data }) => {
store.commit("loadGoodses", data);
});
},
// 設(shè)置所有商品的狀態(tài)
ckAll(store, val) {
store.commit("ckAll", val);
},
// 根據(jù)id刪除商品
delGoodsById(store, id) {
store.commit("delGoodsById", id);
},
},
};
<template>
<div class="shopcart">
<h4>購物車</h4>
<table>
<thead>
<tr>
<th>
<input type="checkbox" v-model="isCkAll" />
</th>
<th>名稱</th>
<th>圖片</th>
<th>單價</th>
<th>數(shù)量</th>
<th>小計</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in goodses" :key="item.id">
<td>
<input type="checkbox" v-model="item.ck" />
</td>
<td>{{ item.name }}</td>
<td>
<img :src="item.img" />
</td>
<td>{{ item.price }}</td>
<td>
<button @click="item.count--" :disabled="item.count === 1">
-
</button>
<input type="text" v-model="item.count" />
<button @click="item.count++" :disabled="item.count === 10">
+
</button>
</td>
<td>{{ item.price * item.count }}</td>
<td>
<button @click="delGoodsById(item.id)">刪除</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="7">
<span>總價:</span>
<span>{{ totalPrice }}</span>
</td>
</tr>
</tfoot>
</table>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from "vuex";
export default {
name: "Shopcart",
computed: {
...mapState("shopcart", ["goodses"]),
...mapGetters("shopcart", ["totalPrice"]),
// 定義可以修改的計算屬性
isCkAll: {
set(val) {
this.ckAll(val);
},
get() {
return this.$store.getters["shopcart/isCkAll"];
},
},
},
methods: {
// 映射actions對應(yīng)的方法
...mapActions("shopcart", ["ckAll", "delGoodsById"]),
},
// 頁面掛載完成
mounted() {
this.$store.dispatch("shopcart/loadGoodses", "data/shopcart.json");
},
};
</script>