vuex 命名空間的使用

vuex 命名空間的使用

廢話不多說,直接上代碼

// store 文件下的index.js
import city from './module/city'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    city
  }
})
// city.js
const state = {
  list: ['a', 'b'],
  count: 0
}

const mutations = {
  mutations_push(state, text) {
    state.list.push(text)
  },
  mutations_add(state) {
    state.count++
  },
  mutations_reduce(state) {
    state.count--
  }
}

const actions = {
  actions_push: ({ commit }, text) => {
    commit('mutations_push', text)
  },
  actions_add: ({ commit }) => {
    commit('mutations_add')
  },
  actions_reduce: ({ commit }) => {
    commit('mutations_reduce')
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}
// 測試頁面 test.vue
<template>
  <div>
    <p>ceshi</p>
    <ul v-if="list.length">
      <li v-for="(item, index) in list" :key="index">{{item}}</li>
    </ul>
    <button @click="push">添加列表</button>
    <br>
    <button @click="add">add</button>
    <span>{{count}}</span>
    <button @click="reduce">reduce</button>
  </div>
</template>

<script>
/* eslint-disable */

// 用法1
// import { mapState, mapActions } from "vuex";

// 用法2
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions } = createNamespacedHelpers("city");

export default {
  data: function() {
    return {};
  },
  computed: {
    // 對應上面的用法1
    // ...mapState("city", {
    //   list: state => state.list
    // })

    // 對應上面的用法2
    ...mapState({
      list: state => state.list,
      count: state => state.count
    })
  },
  methods: {
    // ...mapActions("city", ["actions_push", "actions_add", "actions_reduce"]), // 對應上面的用法1

    ...mapActions(["actions_push", "actions_add", "actions_reduce"]), // 對應上面的用法2

    push() {
      this.actions_push(Math.floor(Math.random() * 100));
      // 直接調用 mutations 中的方法
      // this.$store.commit("city/actions_push", Math.floor(Math.random() * 100));
    },
    add() {
      this.actions_add();
    },
    reduce() {
      this.actions_reduce();
    }
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

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