Vuex 极简入门

在中大型项目中,为方便组件间通讯,因此有了vuex

Vuex 4个核心概念

  • state 用来展示数据
  • getter 用来美化数据
  • mutation 用来计算数据
  • actions 用来异步操作

如何使用

npm install  vuex  --save

在组件中

<template>
  <div>
  	<h3>当前最新的count值为:{{$store.state.count}}</h3>
    <h3>{{$store.getters.showNum}}</h3>
    <button @click="btnHandler2">+N</button>
    <button @click="btnHandler4">+N Async</button>
  </div>
</template>

<script>
export default {
  data() {
    return {}
  },
  methods: {
    btnHandler2() {
      // commit 调用 store.js 中mutation 函数
      this.$store.commit('addN', 3)
    },
    btnHandler4() {
     // dispatch调用 store.js 中actions 函数
      this.$store.dispatch('addNAsync', 5)
    }
  }
}
</script>

store.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  // 只有 mutations 中定义的函数,才有权利修改 state 中的数据
  mutations: {
    addN(state, step) {
      state.count += step
    },
    sub(state) {
      state.count--
    },
    subN(state, step) {
      state.count -= step
    }
  },
  //异步专用
  actions: {
    addNAsync(context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    },
     subAsync(context) {
      setTimeout(() => {
        context.commit('sub')
      }, 1000)
    },
    subNAsync(context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      }, 1000)
    }
  },
  getters: {
    showNum(state) {
      return '当前最新的数量是【' + state.count + '】'
    }
  }
})

使用映射,简化代码

<template>
  <div>
    <!-- <h3>当前最新的count值为:{{count}}</h3> -->
    <h3>{{showNum}}</h3>
    <button @click="btnHandler1">-1</button>
    <button @click="subN(3)">-N</button>
    <button @click="subAsync">-1 Async</button>
    <button @click="subNAsync(5)">-N Async</button>
  </div>
</template>

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

export default {
  data() {
    return {}
  },
  computed: {
    ...mapState(['count']),//映射 State 拿到count的值
    ...mapGetters(['showNum'])//映射 Getters 拿到showNum的值
  },
  methods: {
    ...mapMutations(['sub', 'subN']),// 映射到Mutations
    ...mapActions(['subAsync', 'subNAsync']), //映射到Actions
    btnHandler1() {
      this.sub()
    }
  }
}
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值