什么是Vuex?
是一个公共数据管理工具,可以将共享的数据保存到Vuex里,方便任何组件对这些共享的数据进行调用。
State保存共享数据
通过在根实例(index.js)中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
创建Vuex对象:
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {msg: "yuxuan"},})
state相当于组件中的data,专门用于保存共享的数据。
祖先组件中添加store

子组件都可以使用:
<template id="father"><div><p>{{this.$store.state.msg}}</p></div></template>
前面的this.$store.state是固定的,后面的msg就是其中的某一个共享的数据。
Mutations修改共享数据
以计数器为例,可以在使用的多个子组件里写methods来实现对数据的修改。但是,在Vuex中不推荐直接修改共享数据。因为如果多个组件都修改了共享的数据,那么如果后期数据发生了错误,那么调试将需要一个个组件进行排查,很复杂、低效,不利于维护。
mutations保存方法
在store中使用mutations,这用于保存修改共享数据的方法。
const store = new Vuex.Store({state: {count: 0},mutations: {// 在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数mAdd(state){state.count = state.count + 1;},mSun(state){state.count = state.count - 1;},}})
通过commit使用
子组件通过commit来使用mutations中定义的方法:
Vue.component({methods: {add(){this.store.commit("mAdd");}}})
Getters计算属性
和computed属性类似,计算完后会进行缓存,只有数据发生变化时才会重新计算。
定义
const store = new Vuex.Store({state: {msg: "yonni"},mutations: {// 在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数mAdd(state){state.count = state.count + 1;},},getters: {// 同样也要传递进state参数,函数可以通过参数获得数据formart(state){return state.msg + " ye"}}})
使用
<div>{{this.store.getters.formart}}</div>
