赞
踩
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
组件通过dispatch调用action,action通过commit来触发mutation,mutation来负责修改state,state修改后去重新渲染受影响的dom。
npm install vuex -S
新建:store/index.js。
import vue from 'vue'; import Vuex from 'vuex'; vue.use(Vuex); export default new Vuex.Store({ strict:true,//严格模式,防止直接修改state(性能很差,发布时改为false) state:{ a:1, b:2 }, mutations:{ addA(state,val){ state.a+=val; }, addB(state,val){ state.b+=val; } }, actions:{ addA({commit},val){ //调用mutations中的addA() commit('addA', val); }, addB({commit},val){ //调用mutations中的addB() commit('addB', val); } }, //相当于computed getters:{ getA(state){ return state.a; }, getB(state){ return state.b; }, count(state){ return state.a + state.b; } }, modules:{ } });
import store from './store';
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
state是vuex的核心,是统一存放数据的地方。
从store中获取值。(不推荐)
<template>
<div>
a:{{$store.state.a}}
<br>
b:{{$store.state.b}}
</div>
</template>
官方推荐通过computed来获取,但是如果需要获取多个值就会很麻烦。
<template> <div> a:{{a}} <br> b:{{b}} </div> </template> <script> import {mapState} from 'vuex'; export default { name: "MapState", computed:{ //将store.state中的属性映射到computed ...mapState(['a','b']) } } </script>
获取getters中的值。
<div>
a:{{$store.getters.getA}}
<br>
b:{{$store.getters.getB}}
<br>
a+b={{$store.getters.count}}
</div>
使用mapGetters映射。
<template> <div> a={{getA}} <br> b={{getB}} <br> a+b={{count}} </div> </template> <script> import {mapGetters} from 'vuex'; export default { name: "MapGetters", computed:{ //将store.getters映射到computed ...mapGetters(['getA','getB','count']) } } </script>
通过$store.commit来触发mutation。
不推荐直接调用mutation来修改。
<template>
<div>
a={{$store.state.a}}
<br>
b={{$store.state.b}}
<br>
a+b={{$store.getters.count}}
<hr>
<button @click="$store.commit('add',5)">a+5</button>
</div>
</template>
使用mapMutations映射。
<template> <div> a={{$store.state.a}} <br> b={{$store.state.b}} <br> a+b={{$store.getters.count}} <hr> <button @click="addA(5)">a+5</button> </div> </template> <script> import {mapMutations} from 'vuex'; export default { name: "MapMutations", methods:{ //将store.mutations映射到methods ...mapMutations(['addA']) } } </script>
官方推荐通过action去触发mutation,虽然比较麻烦。
action支持异步,mutation只能同步。
通过$store.dispatch来触发action。
<button @click="$store.dispatch('addA',5)">a+5</button>
使用mapActions映射。
<template> <div> a={{$store.state.a}} <br> b={{$store.state.b}} <br> a+b={{$store.getters.count}} <hr> <button @click="$store.dispatch('addA',5)">a+5</button> </div> </template> <script> import {mapActions} from 'vuex'; export default { name: "MapActions", methods:{ //将store.actions映射到methods ...mapMutations(['addA']) } } </script>
当系统比较庞大时,store会变得非常臃肿。
为了方便store的模块化管理,Vuex 允许我们将 store 分割成 modules。
每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。