vuex的module模塊用法示例

這篇文章主要介紹了vuex的module模塊用法示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

想嘗試使用vuex的module來進行操作,看了一些資料,我簡單進行了一個簡化

目錄結構:

store
│ index.js
│ 
├─feeds
│   actions.js
│   getters.js
│   index.js
│   mutation-type.js
│   mutations.js
│   state.js
│   
└─movies
    actions.js
    getters.js
    index.js
    mutation-type.js
    mutations.js
    state.js

這裏是兩個模塊feeds和movies

第一步:在store文件夾下的index.js入口文件寫入:

import Vue from 'vue';
import Vuex from 'vuex';
import feeds from './feeds';
import movies from './movies';

Vue.use(Vuex);

export default new Vuex.Store({
 modules: {
  feeds,
  movies
 },
});

第二步:在每個模塊內的index文件這組裝所有的零件,並且輸出:

import state from './state';
import mutations from './mutations';
import actions from './actions';
import getters from './getters';

export default {
    namespaced: true, //多出的一行
    state,
    mutations,
    actions,
    getters
};    

注意上面多出的一行,我們在組件裏怎麼區分不同模塊呢?namespaced寫成true,意思就是可以用這個module名作爲區分了(也就是module所在的文件夾名)

第三步:在組件裏使用:

使用的時候

獲取state,這裏使用映射:

import { mapState, mapMutations } from "vuex";

export default {
computed:{
  ...mapStated('模塊名(嵌套層級要寫清楚)',{ //比如'movies/hotMovies
    a:state=>state.a,
    b:state=>state.b
  })
},

觸發actions操作:

import { mapActions } from 'vuex'
methods:{
  ...mapActions('模塊名(嵌套層級要寫清楚)',[ //比如'movies/getHotMovies
    'foo',
    'bar'
  ])
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

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