官网的定义vuex为状态管理模式,能够集中管理组件的状态。vue
假若有好几个不一样地方的组件视图,须要显示同一个数据源,当数据的状态发生改变时,他们也要同时改变。若是使用传参或者复制计算属性来实现,是使代码变得冗余且难以维护。若是组件之间的关系不是父子关系也难以传递。vuex
在怎么用vuex以前,先了解它有什么。
vuex的核心是store对象,store里面能够保存多个state,也就是状态。在根元素建立new Vue({store})的时候引入store,这样就能够全局使用单例状态树,经过$store.state.来获取。
mutation:保存改变状态方法,必须是同步的。commit('func')的方式来改变
getter:用来派生出另外一种状态,例如说判断count是奇数仍是偶数
actions:与mutation相似,但本质是提交mutation,区别在于能够异步请求npm
试想一下,假如一个应用好几个地方都会有判断状态count是奇偶数的需求,若是在每个组件computed:{ evenOrOdd:this.$store.state.count%2===0?'even':'odd' },是否是有一些多余呢,mapGetters能够把getter里的计算属性映射到computed中,让咱们省去了这一部分工做,mapActions同理。异步
1.安装依赖 npm install vuex学习
2.将store单独拎出来管理,建立state,mutation,actions,getters。
定义好状态和方法后,在new Vuex.Store({state,mutation,actions,getters})this
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex) //状态对象 const state = { count:0, times:0 } //改变状态的方法 const mutations = { increment(state){ state.count++ state.times++ }, decrement(state){ state.count-- state.times++ } } // 异步执行 const actions = { increment:({commit}) =>commit('increment'), decrement:({commit}) =>commit('decrement'), isEvenorOdd({commit,state}){ if(state.count%2===0){ commit('increment'); } } } const getters = { evenOrOdd:state => state.count%2===0?'even':'odd' } export default new Vuex.Store({ state, getters, actions, mutations })
3.建立有状态管理的counter.vue组件,经过$store.state....能够获取到状态对象spa
<template> <div class=""> <span @click="decrement">-</span> <span> {{$store.state.count}} </span> <span @click="increment">+</span> <button type="button" name="button" @click="isEvenorOdd">if count is even</button> <p>click {{$store.state.times}} times,count is {{evenOrOdd}}</p> </div> </template> <script> import { mapGetters,mapActions } from 'vuex' export default { computed:{ ...mapGetters({ 'evenOrOdd':'evenOrOdd' }) }, methods:mapActions([ 'increment', 'decrement', 'isEvenorOdd' ]) } </script>
4.在入口文件index.js增长store对象code
new Vue({ router:router, store, render:(h)=> h(App) }).$mount(root)
实现效果router
每次点击次数都会累加,count改变,会判断出count是奇数仍是偶数
当count为偶数时 if count is even 能够点击对象