状态管理优化

在这里插入图片描述
mapgetters直接获取getters方法
mapactions直接获取actions方法
store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//共享变量
const state={
  count:0
}
//直接操作共享变量的对象
const mutations={
  mulincrease(state){
    //自增1
    state.count++;
  }
}
//操作mulations的对象
const actions={
  //自增传入对象,然后调用
  actincrease({commit}){//传多个对象用{}
    commit('mulincrease');
  },
  //异步自增
  asyncincrease({commit}){
    setTimeout(()=>{
      commit('mulincrease')
    },2000)
  }
}
//如果要对共享变量计算,则使用getters,18以下未成年,18岁以上成年了
const getters={
  //是否成年
  isAdult(){
    return state.count>18?'成年':'未成年'
  }
    
}
//将store.js中的对象暴露外界,用于其他组件的共享
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

App.vue

<template>
  <div id="app">
    {{$store.state.count}}
    <!-- <button @click="countinc">同步+</button>
    <button @click="countincAsync">异步+</button> -->
     <button @click="actincrease">同步+</button>
    <button @click="asyncincrease">异步+</button>
    是否成年:{{$store.getters.isAdult}}
    <!-- 是否成年:{{VueisAdult}} -->
    是否成年:{{isAdult}}
  </div>
</template>

<script>
import {mapGetters,mapActions} from 'vuex'
export default {
  // methods:{
  //   countinc(){
  //     //store是一个全局对象,在方法内要用this来拿
  //     this.$store.dispatch('actincrease')
  //   },
  //   countincAsync(){
  //     //store是一个全局对象,在方法内要用this来拿
  //     this.$store.dispatch('asyncincrease')
  //   }
  // },
  methods:mapActions(
    ['actincrease', 'asyncincrease']
  ),
  // computed:{
  //   VueisAdult(){
  //     return this.$store.getters.isAdult
  //   }
  // },
  computed:mapGetters({
    isAdult:'isAdult'//
  })
  
}
</script>

<style lang="scss">

</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值