ibcadmin 发表于 2019-9-26 09:18:06

vuex状态管理

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来获取我们定义的数据
{* index.js
const store = new Vuex.store({state :{count:1// (好比说这个)}})
helloworld.vue**
{{this.$store.state.count}}*}
7.)getters:
getters相当于vue中的computed盘算属性,getter的返回值会根据他的依靠被缓存起来,且只有当他的依靠值发生了改变才会被重新盘算,这里我们可以通过定义vuex的getters来获取,Getters可以用于监听,state中值的变化,返回盘算后的结果
{*helloworld.vue
{{this.$store.state.count}}{{this.$store.getters.getStateCount}}
index.js**
(getStateCount吸收一个参数,这个参数就是 我们用来保存数据的那个对象)
getters:{getStateCount:function(state){return state count + 1}
*}

8.)mutations:
数据在页面获取到了,必要修改count的值,唯一的方法就是提交mutation来修改,在helloworld添加两个按钮,一个加一,一个减一;点击按钮调用addFun(执行加的方法)和 reduction(执行减得方法),然后提交页面的mutation中的方法修改值
{*
count的值:{{this.$store.state.count}} +- methods:{addFun() {this.$store.commit(‘add’)},reductionFun() {this.$store.commit(‘reduction’)}}

index.js**
   (添加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”)},}helloworld.vue**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   })   }
*}
这样我们就不消写很长的方法来调用了。






来源:https://www.cnblogs.com/ivylv/archive/2019/09/24/11581078.html
页: [1]
查看完整版本: vuex状态管理