Vuex

1 篇文章 0 订阅

Vuex

1. state

在store中定义数据,在组件中直接使用

export default new Vuex.Store({
  state: {
    num: 0
  }
})
<template>
  <h1>
    {{$store.state.num}}
  </h1> 
</template>

或者

<template>
  <h1>
    {{num}}
  </h1> 
</template>

<script>
  export default {
    computed: {
      num(){
        return this.$store.state.num
      }
    }
  }
</script>

2.getters

相当于组件中的computed,getters是全局的,computed是组件内部使用的

export default new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
    getNum(state){
      return state.num
    }
  }
})
<template>
  <h1>
    {{$store.getters.getNum}}
  </h1> 
</template>

<script>
  export default {
 
  }
</script>

3.mutations

相当于组件中的methods, 但不能使用异步方法(如定时器, axios等)

export default new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
    getNum(state){
      return state.num
    }
  },
  mutations:{
    increase(state, payload){
      state.num += payload ? payload : 1;
    }
  }
})
<template>
  <div>
    <button @click = "addFn">
      点击加
    </button>
  </div>
</template>

<script>
  export default {
 		methods: {
      addFn(){
        //传参时候,使用payload
        this.$store.commit('increase', 2)
      }
    }
  }
</script>

4. actions

专门用来处理异步,实际修改状态值的,还是mutations

export default new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
    getNum(state){
      return state.num
    }
  },
  mutations:{
    increase(state, payload){
      state.num += payload ? payload : 1;
    }
  },
  actions:{
    increaseAsync(context){
    context.commit('increase')
  }
  }
})
this.$store.dispatch('increaseAsync')

5. 辅助函数

import {mapState} from 'vuex'
import {mapGetters} from 'vuex'

 export default {
 		computed:{
      ...mapState(['num']),
      ...mapGetters(['getNum'])
    }
  }
import {mapActions, mapMutations} from 'vuex'

 export default {
 		methods:{
      ...mapActions(['increaseAsync']),
      ...mapMutations(['increase'])
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值