vuex初识与使用,异步actions和getter

1.什么是 vuex

vuex是一个状态管理工具,所谓状态就是数据。

vuex是一个插件,帮我们解决多组件共享数据的问题(例如:购物车,个人信息)

2. vuex 安装与使用

2.1 安装

npm install vuex@3

2.2 挂载与使用

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store()

export default store

2.3 初始化

const store = new Vuex.Store({
    state:{
        count:200
    }

})

模版访问:

 {{$store.state.count}}

组件里访问:

data() {

   return {

       bucuo:this.$store.state.count

   }

}

3.修改vuex数据 mutaion

const store = new Vuex.Store({

  state:{

   count:200

  },

  mutations: {

     // 第一个参数为 state

     addcount(state,n) {

       // 变更状态,即变更值

        state.count+=n

     }

  }

})

组件:

this.$store.commit('addcount', 2)

4.异步修改数据 action

为什么不直接使用 mutations 因为它只支持同步,不支持异步操作。

action 是专门处理异步操作的

4.1 store 配置

异步修改count ,一秒后变成1000

const store = new Vuex.Store({

  state:{

   count:200

  },

  mutations: {

     // 第一个参数为 state

     addcount(state,n) {

       // 变更状态,即变更值

        state.count+=n

     },

     setcount(state,nums){

        state.count=nums

     }

  },actions:{

   setAsyncCount(context,num){

     setTimeout(()=>{

        context.commit('setcount',num);

     },2000)

   }

  }

})

4.2 组件调用

<button @click="changes(1000)">变变变</button>

<script>

methods:{

   changes(a){

       this.$store.dispatch('setAsyncCount',a);

   }

}

</script>

5关于助手函数 mapMutations 和 mapActions

mapMutations 和 mapState很像,它是把位于mutations中的方法提取了出来,映射到组件methods中。

这2个函数分别是映射 mutations 和 actions

具体用法:

vuex中的store.js

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({

  state:{

   userinfo:{},

cartnum:0

  },

  mutations: {

     //set

     setUserInfo(state,obj){

        state.userinfo=obj

     },

setCartnum(state,n){//修改购物车物品数量

state.cartnum+=n

},

setCartzero(state){//清空购物车

state.cartnum=0

}

  },actions:{//异步

setAsynCartNum(context){

setTimeout(()=>{

context.commit('setCartzero')

},1000)

}

  }

})

export default store

页面中去调用

<!--购物车-->

<div class="shop"  @click="setCartnum(1);" >

   <span >{{$store.state.cartnum}}

   </span>

</div>

<!--清空购物车按钮-->

<div @click="setAsynCartNum" class="dogouwuche">1s清空购物车</div>

<script>

export default{

name:'HomeLay',

data() {

   return {

   lists:[]

   }

},

methods:{

   ...mapMutations(['setCartnum']),

   ...mapActions(['setAsynCartNum'])

}

}

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿John

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值