当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vuex状态管理

vuex状态管理

2019年09月25日  | 移动技术网IT编程  | 我要评论

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}}
<button @click="addfun"> + <button>
<button @click="reductionfun"> - <button>

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
   })
   }

 

*}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网