如果你之前使用過vue.js,你一定知道在vue中各個組件之間傳值的痛苦,在vue中我們可以使用vuex來保存我們需要管理的狀態(tài)值,下面我們就來看一下vuex中常用的一些知識點(diǎn),希望對大家有一定的幫助。
一、為什么要使用Vuex
1、多個組件依賴同一個狀態(tài),使用組件之間通信方法會非常繁瑣,例如多層嵌套組件。
2、需要全局保存的數(shù)據(jù),例如用戶、權(quán)限信息,全局系統(tǒng)設(shè)置
二、Vuex的五個核心屬性
1、state:存儲狀態(tài)
// store.jsconst store = new Vuex.Store({ state: { count: 0 }});// 組件里獲取count值$store.state.count
2、getters:state作為第一個參數(shù),其他getters作第二個參數(shù),返回值會根據(jù)他的依賴緩存起來,相當(dāng)于Vue的計算屬性
// store.jsconst store = new Vuex.Store({ state: { count: 1, sum: 2 }, getters: { getCountAndSum: (state,getters) => { return state.count + state.sum; } }});// 其他組件獲取getter$store.getters.getCountAndSum
3、mutations:修改狀態(tài)(同步的),state 作為第一個參數(shù),提交載荷作為第二個參數(shù)
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state, obj) { state.count += obj.n; } }});// 其他組件調(diào)用mutations的方法$store.commit('increment', {n: 100});
4、actions:異步操作(執(zhí)行mutations的方法,不是直變更狀態(tài))
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state, obj) { state.count += obj.n; } }, actions: { increment (context) { context.commit('increment'); } }});// 其他組件調(diào)用actions的方法$store.dispatch('increment');
5、modules:store的子模塊
const a = { state: { count: 0 }, getters: { getCount2 (state, getters, rootState) { return state.count + 2; } }, mutations: { increment (state, getters, rootState) { state.count++; } }, actions: { increment (context) { // context.state.count; // context.rootState.count; context.commit('increment'); } }};const b = {};const store = new Vuex.Store({ modules: { a, b }});// 其他組件調(diào)用 (獲取state的變量需要加上引入的module的別名)$store.state.a$store.state.b
三、Vuex輔助函數(shù)
<template> <div class="about"> <h1>count: <span>{{count}}</span></h1> <h1>getCount: <span>{{$store.getters.getCount}}</span></h1> <h1>sum: <span>{{sum}}</span></h1> <h1>getSum: <span>{{$store.getters.getSum}}</span></h1> <button @click="clickB">test </button> </div></template><script>import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'; export default { name: 'about', data () { return { count: 0, sum: 0 } }, computed: { ...mapState({ count: state => state.count, countAlias: 'count', countPlusLocalState (state) { return state.count + this.localCount; } }), ...mapGetters([ 'getCount', 'getSum' ]) }, mounted () { this.count = this.$store.state.count; this.sum = this.$store.state.a.sum; }, methods:{ ...mapMutations( 'add','addO' ), ...mapActions([ 'add','addO' ]), clickB () { this.$store.dispatch('add'); this.$store.dispatch('addO'); } } }</script>