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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章