1. 程式人生 > 其它 >VueX分了模組如何使用

VueX分了模組如何使用

技術標籤:javascriptvue.jses6html5

VueX分了模組如何使用

1、建立一個js檔案,命名為ad的一個VueX的子模組

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

Vue.use(Vuex)

const ad= ({
  namespaced: true, //定義名稱空間,防止衝突
  state: {
    adStyleShow : true
  },
  mutations: {
    setAdStyleShow (state,flag) {
      state.adStyleShow = flag
    }
, } }) export default ad

2、然後再index.js中引入該子模組

import Vue from 'vue'
import Vuex from 'vuex'
import ad from './module/ad'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user
  }
})

3、然後在Vue元件使用,首先如何獲取state裡面的值,有兩種方法

//法一:直接用$store返回
computed:{ show(){ return this.$store.state.ad.adStyleShow //show為該vue組建中的變數名,ad為VueX模組的名字,adStyleShow為state裡的值 } } //法二:用mapState對映 import { mapState} from "vuex" computed:{ ...mapState({ show : state=> state.ad.adStyleShow //show為該vue組建中的變數名,ad為VueX模組的名字,adStyleShow為state裡的值
}) }

這兩種方法都可以得到show的值為ad模組中state的adStyleShow值在這裡插入圖片描述

4、如何使用mutations

<template>
<button @click="adStyleChange"></button>
</template>

<script>
import { mapState, mapMutations } from "vuex"
 methods: {
      ...mapMutations("ad",["setAdStyleShow"]), //對映ad模組中的Mutations的setAdStyleShow方法
      
      adStyleChange(){
          this.setAdStyleShow(false)
      }
}
</script>