vuex store模組化
阿新 • • 發佈:2020-12-26
技術標籤:Vuevuex store模組化
上一篇的文章主要是講解vuex中的簡單使用,所以幾乎把所有程式碼都寫在index.js一個資料夾裡面,但是如果專案龐大時,這樣不好維護。所以現在把index中的state、actions、getters、mutations分別獨立出來
首先在store中建立以下檔案:
以下對之前index.js進行改造
之前的index.js
import Vue from 'vue'
import Vuex from 'vuex'
import { getHotArticle } from '../api/index'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//熱門文章
hotArticle: []
},
mutations: {
getHotArticleList(state, data) {
state.hotArticle = data;
console.log(state.hotArticle)
},
},
actions: {
//獲取熱門文章
async getHotArticleList({ commit }, limitcount) {
let result = await getHotArticle(limitcount);
commit('getHotArticleList', result.data)
}
},
modules: {
}
})
然後將state中的資料寫在state.js中
export default{
//熱門文章
hotArticle: []
}
然後建立一個mutations-types對mutations使用過的方法進行常量定義
mutations-types如下:
export const GETHOTARTICLELIST = "getHotArticleList" ; //getHotArticleList常量
actions.js
import {
GETHOTARTICLELIST
} from './mutation-types'
import {getHotArticle} from '../api/index'
export default {
//獲取熱門文章
async getHotArticleList({ commit }, limitcount) {
let result = await getHotArticle(limitcount);
commit(GETHOTARTICLELIST, result.data)
}
}
mutations.js
import {
GETHOTARTICLELIST
}from './mutation-types'
export default{
[GETHOTARTICLELIST](state,hotArticle){
state.hotArticle = hotArticle;
},
}
最後index.js
import Vue from "vue"
import Vuex from "vuex"
import state from "./state"
import getters from "./getters"
import actions from "./actions"
import mutations from "./mutations"
Vue.use(Vuex)
export default new Vuex.Store({
state,
getters,
actions,
mutations
})