请选择 进入手机版 | 继续访问电脑版

马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

vuex状态管理

[复制链接]
查看2153 | 回复0 | 2019-9-26 09:18:06 | 显示全部楼层 |阅读模式
vuex状态管理

在vue中我们可以利用vuex来保存我们必要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新。

1.)新建一个vue项目
  1. vue init webpack web  //(利用webpack创建一个项目名为web的项目)
复制代码

2.)安装vuex
  1. npm install vuex --save
复制代码

3.)启动项目
  1. npm run dev
复制代码
  
4.)在src目次下新建一个目次store,在该目次下新建一个index.js的文件,用来创建vuex实例,然后在该文件中引入vue 和 vuex,创建vuex.store实例保存到变量store中,末了export default导出store
{*
  1. const store = new Vuex.Store({})export default store;
复制代码

*}
5.)在main.js文件中引入该文件
在文件里面添加 import store from “./store”
{*
  1. new Vue({el:"#app",store,router,...})
复制代码
*}

6.)state:
vuex中的数据源,我们必要保存的数据就保存在这里,可以在页面通过this.$store.state来获取我们定义的数据
{* index.js
  1. const store = new Vuex.store({state :{count:1  // (好比说这个)}})
复制代码

helloworld.vue**
  1. {{this.$store.state.count}}
复制代码
*}
7.)getters:
getters相当于vue中的computed盘算属性,getter的返回值会根据他的依靠被缓存起来,且只有当他的依靠值发生了改变才会被重新盘算,这里我们可以通过定义vuex的getters来获取,Getters可以用于监听,state中值的变化,返回盘算后的结果
{*helloworld.vue
  1. {{this.$store.state.count}}{{this.$store.getters.getStateCount}}
复制代码

index.js**
(getStateCount吸收一个参数,这个参数就是 我们用来保存数据的那个对象)
  1. getters:{getStateCount:function(state){return state count + 1}
复制代码

*}

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


index.js**
   (添加mutation,在mutation中定义两个函数,用来对count加1和减1,就是上面commit提交的两个方法)
  1. 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的函数
{*
  1. actions:{addFun(context){context.commit(“add”)},reductionFun(context){context.commit(“reduction”)},}
复制代码
  1. helloworld.vue**
复制代码
  1. 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

{*
  1.    import {mapState、mapGetters、mapActions} from 'vuex';   computed:{   ...mapState({   count1:state  => state.count   })   }
复制代码

*}
这样我们就不消写很长的方法来调用了。






来源:https://www.cnblogs.com/ivylv/archive/2019/09/24/11581078.html
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则