Vue 配置vuex

vuex实现了统一状态管理,这里记录基础配置及使用方法

//store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 1,
    isShow: true
  },
  mutations: {
    increment (state) {
      state.count++
    },
    decrement (state) {
      state.count--
    },
    toggleState (state) {
      state.isShow = !state.isShow
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    },
    decrement (context) {
      context.commit('decrement')
    },
    incrementIfOdd ({commit, state}) {
      if (state.count % 2 == 1) commit('increment')
    },
    incrementAsync ({commit}) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    },
    toggleState ({commit}) {
      commit('toggleState')
    }
  },
  getters: {
    evenOrOdd (state) {
      return state.count % 2 == 0? '偶数': '奇数'
    }
  },
  modules: {}
})
<template>
  <div id="">
  	<!-- MyStoreDemo组件 -->
    <div class="vuex">
      <h1>Vuex 示例</h1>
      <el-button :type="isShow==false?'primary':'danger'" v-text="isShow==false?'显示':'隐藏'"
                 @click="toggleState"></el-button>
      <template v-if="isShow">
        <p class="p-vuex">click {{count}} times, count is {{evenOrOdd2}}</p>
        <el-button type="primary" @click="increment">增加</el-button>
        <el-button type="primary" @click="decrement">减少</el-button>
        <el-button type="primary" @click="incrementIfOdd">奇数增加</el-button>
        <el-button type="primary" @click="incrementAsync">异步增加</el-button>
      </template>
    </div>
  </div>
</template>

<script>
  import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

  export default {
    name: 'MyStoreDemo',
    data() {
      return {}
    },
    computed: {
      ...mapState(['count', 'isShow']),
      ...mapGetters({'evenOrOdd2': 'evenOrOdd'}),
      // count () {
      //   return this.$store.state.count
      // },
      // evenOrOdd2 () {
      //   return this.$store.getters.evenOrOdd
      // }
    },
    methods: {
      ...mapMutations(['increment', 'decrement']),
      ...mapActions(['incrementIfOdd', 'incrementAsync', 'toggleState']),
      // increment () {
      //   this.$store.dispatch('increment')
      // },
      // decrement () {
      //   this.$store.dispatch('decrement')
      // },
      // incrementIfOdd () {
      //   this.$store.dispatch('incrementIfOdd')
      // },
      // incrementAsync () {
      //   this.$store.dispatch('incrementAsync')
      // },
      // toggleState () {
      //   this.$store.dispatch('toggleState')
      // }
    }
  }
</script>

<style scoped>
  .p-vuex {
    line-height: 30px;
    font-size: 20px;
  }
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值