vuex状态管理
在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新。
1. 新建一个vue项目
vue init webpack web //(使用webpack创建一个项目名为web的项目)
2. 安装vuex
npm install vuex --save
3. 启动项目
npm run dev
4. 在src目录下新建一个目录store,在该目录下新建一个index.js的文件,用来创建vuex实例,然后在该文件中引入vue 和 vuex,创建vuex.store实例保存到变量store中,最后export default导出store
const store = new Vuex.Store({}) export default store;
5. 在main.js文件中引入该文件
在文件里面添加 import store from “./store”
new Vue({ el:"#app", store, router, ... })
6. state:
vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过this.$store.state来获取我们定义的数据
const store = new Vuex.store({ state :{ count:1 // (比如说这个) } })
页面引用
{{this.$store.state.count}}
7. getters:
getters相当于vue中的computed计算属性,getter的返回值会根据他的依赖被缓存起来,且只有当他的依赖值发生了改变才会被重新计算,这里我们可以通过定义vuex的getters来获取,Getters可以用于监听,state中值的变化,返回计算后的结果
页面引用方法
{{this.$store.state.count}} {{this.$store.getters.getStateCount}}
getStateCount接收一个参数,这个参数就是 我们用来保存数据的那个对象-----》vuex中getters写法如下
getters:{ getStateCount:function(state){ return state count + 1 }
8. mutations:
数据在页面获取到了,需要修改count的值,唯一的方法就是提交mutation来修改,在helloworld添加两个按钮,一个加一,一个减一;点击按钮调用addFun(执行加的方法)和 reduction(执行减得方法),然后提交页面的mutation中的方法修改值
count的值:{{this.$store.state.count}} <button @click="addFun"> + <button> <button @click="reductionFun"> - <button> methods:{ addFun() { this.$store.commit(‘add’) }, reductionFun() { this.$store.commit(‘reduction’) } }
添加mutation,在mutation中定义两个函数,用来对count加1和减1,就是上面commit提交的两个方法
mutation:{ add(state){ state.count = state.count + 1; }, reduction(state){ state.count = state.count - 1; }, }
9. Actions:
官方并不建议直接去修改store中的值,而是让我们去提交一个actions,在actions中提交mutation再去修改状态值,在index.js里面去修改,定义actions提交mutation的函数
actions:{ addFun(context){ context.commit(“add”) }, reductionFun(context){ context.commit(“reduction”) }, }
methods:{ addFun(){ this.$store.dispatch("addFun"); //this.store.commit("add") }, reductionFun(){ this.$store.dispatch("reductionFun") }
}
这里把commit提交mutations修改为dispatch来提交actions,效果相同
如果需要指定加减的数值,那么直接传入dispatch的第二个参数,然后在actions中对应的函数中接收参数传递给mutations中的函数进行计算
10.
mapState、mapGetters、mapActions
import {mapState、mapGetters、mapActions} from 'vuex'; computed:{ ...mapState({ count1:state => state.count }) }
以上就是vuex状态管理最基本的概念