Vue03_Vuex的基本使用


  • 安装 vuex 的依赖包
npm install vuex --save
  • vuex 配置 js
import { createStore } from 'vuex'

export default createStore({
  state: {
    count: 0
  },
  mutations: {
    // 不要在mutations中定义异步任务,需要借助actions来实现异步
    add (state, step) {
      state.count += step
    },
    sub1 (state, step) {
      state.count -= step
    },
    sub2 (state, step) {
      state.count -= step
    }
  },
  actions: {
    addAsync (context, step) {
      setTimeout(() => {
        // actions不能直接修改state中的数据,需要通过调用mutations的方法来间接修改
        context.commit('add', step)
      }, 1000)
    },
    add2Async (context, step) {
      setTimeout(() => {
        context.commit('add', step)
      }, 2000)
    }
  },
  // getters的作用是包装state中的数据
  getters: {
    showNum (state) {
      return '当前最新的count值为:【' + state.count + '】'
    }
  },
  modules: {}
})
  • App.vue
<template>
  <div>
    <div>Hello,World!</div>
    <div><my-addition></my-addition></div>
    <div><my-subtraction></my-subtraction></div>
  </div>
</template>

<script>
import Addition from './components/add.vue'
import Subtraction from './components/sub.vue'

export default {
  data () {
    return {}
  },
  components: {
    'my-addition': Addition,
    'my-subtraction': Subtraction
  }
}
</script>

<style>
</style>
  • add.vue
<template>
    <div>
        <!-- 直接从 state 中取值 -->
        <p>count 的值为:{{$store.state.count}}</p>
        <button @click="add">+1</button>
        <button @click="add2">+2</button>
    </div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    ...mapActions(['add2Async']),
    add: function () {
      // dispatch用于调用actions中的函数
      this.$store.dispatch('addAsync', 1)
    },
    // 另一种调用Actions函数的方法
    add2: function () {
      this.add2Async(2)
    }
  }
}
</script>
  • sub.vue
<template>
    <div>
        <p>count 的值为:{{count}}</p>
        <!-- 从getters中取值 -->
        <p>{{$store.getters.showNum}}</p>
        <p>{{showNum}}</p>
        <button @click="s1">-1</button>
        <button @click="s2">-2</button>
    </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    // 另一种调用mutations中的函数的方法
    ...mapMutations(['sub1']),
    s1: function () {
      this.sub1(1)
    },
    s2: function () {
      // 通过commit调用mutations中的函数
      this.$store.commit('sub2', 2)
    }
  },
  computed: {
    // 通过 mapState 从 state 中取值
    ...mapState(['count']),
    // 通过 mapGetters 从 getters中取值
    ...mapGetters(['showNum'])
  }
}
</script>

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐