vuex是一个专门为vue.js设计的集中式状态管理架构。
一、 安装vuex
cnpm install vuex --save
二、 关于store.js
1.创建管理vuex的文件夹和文件并引入和使用
在src内新建一个vuex文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。
import Vue from 'vue'; //引入文件
import Vuex from 'vuex';
Vue.use(Vuex); //使用
2.创建需要共享的状态常量
const state={
count:1
}
3.用export default 封装代码,让外部可以引用。
export default new Vuex.Store({ //Store是Vuex的一个核心方法,字面上理解为“仓库”的意思
state
})
三、 关于count.vue
1.在components目录下新建count.vue ,并引入store.js
<template>
<div>
<h3>{{$store.state.count}}</h3> //1
</div>
</template>
<script>
import store from '@/vuex/store'
export default{
store
}
</script>
四、获取state(把store.js内的count 值传到vue的data)
1.通过computed的计算属性直接赋值
computed:{
count(){
return this.$store.state.count;
}
}
2.通过mapState的对象来赋值
import {mapState} from 'vuex'; //必须加{}
computed:mapState({
count:state=>state.count //es6
})
computed: mapState({ //es5
count:function(state){
return state.count
}
}),
3.通过mapState的数组来赋值
computed:mapState(["count"])
4.通过以上三种方法,即可通过{{count}}获取到值而不是{{$store.state.count}}
五、 修改state
-
1.——Mutations(同步)
-
1.——actions(异步)
六、getters计算过滤操作
getters从表面是获得的意思,可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工。你可以把它看作store.js的计算属性。
例如:对store.js文件中的count进行一个计算属性的操作,就是在它输出前,给它加上100.
-
基本写法
-
1.store.js里用const声明getters属性
const getters = { countgetters:function(state){ //countgetters 方法名 return state.count +=100; } }
-
2.暴露
export default new Vuex.Store({ state,mutations,getters })
-
3.在count.vue中配置
computed:{ ...mapState(["count"]), //前面的mapState方法 count(){ return this.$store.countgetters } },
-
-
引入mapGetters以简化写法
七、module模块组
computed:{
count(){
return this.$store.state.a.count;
}
},
总结:
store.js :定义→暴露
const state={
count:1
}
↓
export default new Vuex.Store({
state,mutations,actions
})
vue:引入→暴露
mapState,mapGetters→computed;
mapMutations,mapActions→methods
import { mapState,mapMutations,mapActions } from "vuex";
↓
export default {
computed: mapState({
count: state => state.count //es6
}),
methods: {
...mapMutations(["add", "reduce"]),
...mapActions(["addAction", "reduceAction"])
},
store
};