基本使用
1.安装依赖
npm install vuex --save
2.导入
import Vuex from 'vuex' Vue.use(Vuex)
3.创建store对象
const store = new Vuex.store({ //state中存放的是全局共享的数据 state:{count:0} })
4.将store对象挂载在vue实例中
new Vue({ el:'#app', render: h => h(app), router, //将创建的共享数据对象挂载到vue实例中 //所有组件都可以直接从store中获取全局的数据 store })
核心概念
1.state
//提供唯一的公共数据 const store = new Vuex.Store({ state:{count:0} })
组件访问state中数据的方式
第一:this.$store.state.全局数据名称
第二:
{{count}}//直接用 //1.导入mapState函数 import {mapState} from 'vuex' //2.将全局数据映射为当前组件的计算属性 computed:{ ...mapState(['count']) }
2.Mutation (用于修改store中的数据,方便查找问题)
触发mutation的方式:
第一:
不要在组件中直接修改state中的数据
//定义mutation const state = new Vuex.Store({ state:{count:0}, mutations:{ //在此变更状态 add(state){ state.count++ } } }) //在组件中触发mutation methods:{ handle1(){ this.$store.commit('add') } }
可以在触发mutation时传递参数
add(state,step){state.count +=step} handle2(){this.$store.commit('add',3)}
第二:
//1.从vuex中导入mapMutations函数 import {mapMutations} from 'vuex' //2.将在指定的mutation函数映射为当前组件的methods函数 methods:{ ...mapMutation(['add','addN']) }
3.Action(用于处理异步任务)
异步操作不能使用mutation,必须使用action
但Action中还是通过触发mutation的方式间接修改数据
触发action的方式: 第一:
//定义Action const store = new Vuex.Store({ //...省略state mutations:{ add(state){ state.count++ } }, actions:{ addAsync(context){ setTimeout(() => { context.commit('add') }) } } }) //在组件中触发action methods:{ handle(){ //触发action的第一种方式 this.$store.dispatch('addAsync') } }
触发actions也可以携带参数,方法如上步骤
第二:
//1.导入mapActions函数 import {mapActions} from 'vuex' //2.将指定actions函数,映射为当前组件的methods函数 methods:{ ...mapActions(['addAsync','addNAsync']) }
4.getter(类似vue中的计算属性,起到包装作用,同步跟随store中的是数据变化)
//定义getter const store = new Vuex.Store({ state:{count:0}, getters:{ showNUm:state => { return `当前最新的数量是${state.count}` } } }) //使用getter的两种方式 1. this.$store.getters.名称 2. import {mapGetters} from 'vuex' computed:{ ...mapGetters(['showNum']) }