1. 程式人生 > >No.03---Vue進階之模塊化組織

No.03---Vue進階之模塊化組織

謝謝 zh-cn ram set vuex msg mit methods span

前兩篇講解了一下 Vuex 的基本使用方法,可是在實際項目中那麽寫肯定是不合理的,如果組件太多,不可能把所有組件的數據都放到一個 store.js 中的,所以就需要模塊化的組織 Vuex,首先看一下 項目結構

技術分享圖片 項目結構
一、首先執行以下命令:

vue init webpack-simple vuex-demo
cd vuex-demo
npm install
npm install vuex -S
npm run dev

二、按照上圖結構創建文件目錄
技術分享圖片 Vuex 模塊化目錄
三、編寫文件

我們就延用上兩篇文章中的例子。先說一個各個文件的作用

types.js

內定義常量,使用常量替代 mutation 事件類型
user.js 內寫該 user 組件內用到的 stategettersactionsmutations,並最後統一導出(類似上個例子中的 store.js )
getters.js 內寫原來的 getters ,用來獲取屬性
actions.js 內寫原來的 actions ,就是要執行的動作,如流程的判斷、異步請求
index.js 是用來組裝 actions.js 、 getters.js 、user.js 的,然後進行統一的導出

1. 在 main.js 中導入 index.js 文件並註冊
import Vue from ‘vue‘
import App from ‘./App.vue‘
import store from ‘./store/index.js‘

new Vue({
  store,
  el: ‘#app‘,
  render: h => h(App)
})
2. 在 types.js 內定義 常量 並導出,默認全部大寫
// 定義類型常量,默認全部大寫
const INCREMENT = ‘INCREMENT‘
const DECREMENT = ‘DECREMENT‘

export default {
    INCREMENT,
    DECREMENT
}

註意:把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的 mutation 一目了然。用不用常量取決於你——在需要多人協作的大型項目中,這會很有幫助。但如果你不喜歡,你完全可以不這樣做。

3. user.js 內寫該 user 組件內用到的 stategetters
actionsmutations
// 導入 types.js 文件
import types from "./../types";

const state ={
    count:5
}

// 定義 getters
var getters ={
    count(state){
        return state.count
    }
}

const actions ={
    increment({ commit, state }){
        // 此處提交的事件與下方 mutations 中的 types.INCREMENT 對應,與原來 commit(‘increment‘) 的原理相同,只是把類型名換成了常量
        commit(types.INCREMENT)
    },
    decrement({commit,state}){
        if (state.count>10) {
            // 此處提交的事件與下方 mutations 中的 types.DECREMENT 對應
            commit(types.DECREMENT)
        }
    }
}

const mutations ={
    // 此處的事件為上方 actions 中的 commit(types.INCREMENT)
    [types.INCREMENT](state){
        state.count++
    },
    // 此處的事件為上方 actions 中的 commit(types.DECREMENT)
    [types.DECREMENT](state){
        state.count--
    }
}
// 最後統一導出
export default {
    state,
    getters,
    actions,
    mutations
}

註意:上方 mutations 中的 [types.INCREMENT] 寫法,因為 types.INCREMENT 是一個對象,所以不能直接當做一個函數名來寫,需要用到 ES2015 風格的計算屬性命名功能來使用一個常量作為函數名,方能正常使用,原來的寫法為:

const mutations ={
    increment(state){
        state.count ++;
    }
}
4. getters.js 內寫原來的判斷奇偶數方法
// 因為數據從 user.js 中獲取,所以需要引入該文件
import user from ‘./modules/user‘

const getters = {
    isEvenOrOdd(state){
        // 註意數據是從 user.js 中獲取的,所以寫成 user.state.count
        return user.state.count % 2 == 0 ? "偶數" : "奇數"
    }
}
// 並導出
export default getters;
5. actions.js 內寫原來的異步操作
// 異步操作中需要用到 increment 方法,所以需要導入 types.js 文件
import types from ‘./types‘

const actions= {
    incrementAsync({ commit, state }) {
        // 異步操作
        var p = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve()
            }, 3000);
        });
        p.then(() => {
            commit(types.INCREMENT);
        }).catch(() => {
            console.log(‘異步操作‘);
        })
    }
}
// 最後導出
export default actions;
6. 在 index.js 中組裝 actions.js 、 getters.js 、user.js 的,然後統一導出
import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

import getters from ‘./getters‘
import actions from ‘./actions‘
import users from ‘./modules/user‘
// 導出 store 對象
export default new Vuex.Store({
    getters,
    actions,
    modules:{
        users
    }
})

註意:在導出 store 對象時,因為 gettersactionsvuex 的核心概念中有默認,可以直接寫入。但是 users 不是默認的,所以用到 vuex 中的 modules 對象進行導出

技術分享圖片 核心概念

7. Vue.app 文件不作任何修改
<template>
  <div id="app">
    <button @click="increment">增加</button>
    <button @click="decrement">減少</button>
    <button @click="incrementAsync">延時增加</button>
    <p>{{count}}</p>
    <p>{{isEvenOrOdd}}</p>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
export default {
  name: ‘app‘,
  data () {
    return {
      msg: ‘Welcome to Your Vue.js App‘
    }
  },
  computed:mapGetters([
    ‘count‘,
    ‘isEvenOrOdd‘
  ]),
  methods:mapActions([
    ‘increment‘,
    ‘decrement‘,
    ‘incrementAsync‘
  ])
}
</script>

最後,驚心動魄的時候到了,我這費半天勁的東西到底能不能跑起來


技術分享圖片 vuex模塊化.gif

對於新手們來說,光是看一次可能很難理解這個過程,還是要親自多試一試的,有什麽問題,歡迎留言,謝謝觀摩!

No.03---Vue進階之模塊化組織