Vuex的基本使用跟逻辑

这里仅展示vue-cli中使用vuex的基本流程跟顺序,这里不讲vuex如何引入项目中

一、首先是最基本的定义一个全局变量state

const state = {
  count: 1,
}

我们在使用的时候需要取出这个全局变量,有两种方式

第一种,直接在template中使用

<template>
  <div>
      $store.state.count
  </div>
</template>

第二种,导入mapState然后在计算属性中使用

import { mapState } from 'vuex'

<template>
  <div>
    {{count}}
  </div>
</template>

computed: {
    ...mapState({'count'}),
  },

二、假设我们需要修改state中的值,此时我们就需要使用mutations

定义一个mutations方法对state中的值进行修改

const mutations = {
  ADD_COUNT: (state, view) => {
    state.count += view
  }
}

第一种修改方式,直接在方法中调用commit修改state的值

this.$store.commit('ADD_COUNT', 3)

 第二种修改方式,引入mapMutation

import { mapMutations } from 'vuex'

//然后在methods中对使用这个方法

methods: {
    ...mapMutations({
      add: 'ADD_COUNT' // 将 `this.add()` 映射为 `this.$store.commit('ADD_COUNT')`
    })

    //调用
    this.add(3)

  }

三、但是假设你需要使用个定时器,异步地修改state的值,你会发现mutations无法修改到state中的值,这个时候你就需要使用到action 

定义一个action 

const actions = {
  asyncAddCount({ commit },num) {

    setTimeout(()=>{
        //注意这里调用的是mutations中的提交方法 
       commit('ADD_COUNT',num)
    },1000)

  },
}

 第一种使用方式

//methods中直接修改,跟commit差不多
this.$store.dispatch('asyncAddCount',3)

第二种,使用mapAction,跟mapMutations差不多

    ...mapActions({
      add: 'asyncAddCount' // 将 `this.add()` 映射为 `this.$store.dispatch('asyncAddCount')`
    })
       
    this.add(3)

四、假设你需要取出state时做一些判断或者过滤,比如state是1,你取出来想要乘2,就可以使用getter

定义一个getter

  getters: {
    getCount: (state) => {
      return state.count * 5
    }
  }

取的话就跟state的取差不多

第一种

this.$store.getters.getCount

第二种

<template>
    <div>{{getCount}}</div>
</template>


import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'getCount'
    ])
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值