Vuex是什么
首先Vuex是一个存储器,可以像localStorage一样存储数据,不同的是Vuex可以和vue进行联动,存储在Vuex中的数据发生变化后会,相应的组件也会相应地得到高效更新,一定程度上他和vue的computed方法很像,不同的是它存储的是全局数据,可以在任何地方提取,父子组件传值、兄弟组件传值都可以使用Vuex取代原来的方式。
一个简单实例
这里引用一个官方文档中的实例,简单描述一下Vuex的使用。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } }) // 在组件中使用 <template> <div> <h2>{{ $store.state.count }}</h2> <div> <button @click="$store.commit('increment')">add</button> </div> </div> </template> <script> import store from '@/vuex/store' export default { store } </script>
State
从store实例中读取状态最简单的方法是在计算属性中返回某个状态
const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return store.state.count } } }
第二种是使用mapState
import store from '@/vuex/store' import { mapState } from 'vuex' export default { store, computed: mapState({ count: state => state.count }), }
第三种同样是使用mapState但比第二种更加简便
export default { store, computed: mapState(['count']), }
Mutations修改状态
mutations的用法已经在简单例子处标明。如果想要在模版中更友好的显示可以用下面的方法
<template> <div> <h2>{{ $store.state.count }}</h2> <div> <button @click="increment">add</button> </div> </div> </template> <script> import store from '@/vuex/store' import { mapState, mapMutations } from 'vuex' export default { store, computed: mapState(['count']), methods: mapMutations(['increment']), } </script>
actions异步修改状态
上面的Mutations是同步修改状态,当需要异步修改的时候,可以用下面的方法。
const state = { count: 1 }; const mutations = { increment (state, n) { state.count += n; }, }; const actions = { // 同步 syncActions (context) { context.commit('increment', 10); }, // 异步 asyncActions ({ commit }) { commit('increment', 10); setTimeout(() => {console.log('我先等着')), 3000}); console.log('异步先加载我'); } }; export default new Vuex.Store({ state, mutations, actions }); // 组件中使用 import { mapState, mapMutations, mapActions } from 'vuex' export default { store, computed: { ...mapState(['count']) }, methods: { ...mapMutations([increment']), ...mapActions(['syncActions', 'asyncActions']), }, }
modules模块分组
随着共享的状态增多,会变得难以维护,此时可以使用module将状态分组。
const moduleA={ state,mutations,getters,actions } export default new Vuex.Store({ modules:{a:moduleA} }) computed:{ count(){ return this.$store.state.a.count; } },
来源:https://www.cnblogs.com/peilanluo/p/10315521.html