vuex是一个专门为vue.js应用程序开发的状态管理模式。即data中属性同时有一个或几个组件同时使用,就是data中共用的属性。
安装vuex
知识点
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 44 } const getters = { count:function(state){ return state.count += 100; } } const mutations = { jia(state,n){ state.count += n; }, jian(state){ state.count-- } } const actions = { jiaplus(context){ // context 整个Store context.commit('jia',{a:1}); setTimeout(()=>{ context.commit('jian'); },3000); console.log('我先被执行了!'); }, jianplus({commit}){ commit('jian'); } } export default new Vuex.Store({ state, getters, mutations, actions })
1. State
访问状态对象:常量,数字,不变的
$store.state.count; import {mapState} from 'vuex'; export default{ computed:mapState(["count"]) }
2.Getters
计算属性
import {mapState,mapGetters} from vuex export default{ computed:{ ...mapState(['count']), //count(){ // return this.$store.getters.count //} ...mapGetters(['count']) } }
3.Mutations
方法对象,触发状态。
import {mapMutations} from 'vuex'; export default{ methods:mapMutations([ 'jia', 'jian' ]) } <button @click="$store.commit('jia',10)">+</button> //commit 触发方法 <button @click="jian">-</button>
4.Actions
异步触发状态
import {mapState,mapMutations,mapActions} from 'vuex'; export default{ computed:{ ...mapState(['count']) }, methods:{ ...mapMutations(['jian','jia']), ...mapActions(['jiaplus']), ...mapActions({jianplus:'jianplus'}) } } <button @click="jiaplus">+</button> <button @click="jianplus">-</button>
5.module
参考
Vuex学习笔记(-)安装vuex: https://www.cnblogs.com/chengkun101/p/7979153.html