精品伊人久久大香线蕉,开心久久婷婷综合中文字幕,杏田冲梨,人妻无码aⅴ不卡中文字幕

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Vuex下Store的模塊化拆分實踐

前言

最近的項目用到了 vue.js + vuex + vue-router 全家桶,版本為 >2.0,在搞Store的時候發現,圈子里大部分關于vuex的文章都是比較基礎的Demo搭建方式,很少有涉及到比較復雜的模塊化拆分的Store實踐,而且事實上也有朋友在實踐中問到過這方面的內容,vuex自身提供了模塊化的方式,因此在這里總結一下我自己在項目里的心得。

模塊化拆分

vue.js的項目文件結構在這里就不說了,大家可以通過vue-cli初始化項目,腳手架會為你搭建一個start項目的最佳實踐。

默認你已經搭架好了一個項目,而且需要建立或者已經是一個復雜的Store,但是還沒有進行模塊拆分,你可以嘗試對其進行模塊拆分,當然在一開始你不必一定需要這么做。

1. 安裝Vuex,建立文件結構

在項目根目錄下安裝vuex:

npm install vuex -S

安裝完畢后,在項目的src文件夾下新建一個store文件夾,并且分別在其中新建modules,actions,mutations,getters,constants子文件夾和一個index.js文件。

目錄結構如下:

└─ demo/   ├── build/   ├── config/   ├── node_modules/   ├── src/   │   ├── assets/   │   ├── components/   │   ├── store/   │   │   ├── actions/    │   │   │   ├──aAction.js   │   │   │   ├──bAction.js   │   │   │   └──cAction.js   │   │   ├── constants/   │   │   │   └── types.js   │   │   ├── getters/   │   │   │   └── aGetter.js   │   │   ├── modules/   │   │   │   ├── aModules.js   │   │   │   ├── bModules.js   │   │   │   ├── cModules.js   │   │   │   └── index.js   │   │   ├── mutations/   │   │   │   ├── aMutation.js   │   │   │   ├── bMutation.js   │   │   │   └── cMutation.js   │   │   └── index.js   │   ├── App.vue   │   └── main.js   ├── static/   ├── utils/   ├── test/   └── index.html

好了,基本的文件結構大概就是上面??這樣的。

2. 編寫模塊A

在編寫模塊之前,首先設定一些type類,例如:

types.js

module.exports = keyMirror({    FETCH_LIST_REQUEST: null,    FETCH_LIST_SUCCESS: null,    FETCH_LISR_FAILURE: null    })function keyMirror (obj) {  if (obj instanceof Object) {    var _obj = Object.assign({}, obj)    var _keyArray = Object.keys(obj)    _keyArray.forEach(key => _obj[key] = key)    return _obj  }}

上面??自己實現keyMirror的方法,大家也可以使用下面這個包:
github.com/STRML/keyMirror

keyMirror的作用就是下面這個一個形式??,作用其實也不是很大:

Input: {key1: null, key2: null}

Output: {key1: key1, key2: key2}

actions/aAction.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from  '../constants/types'import { toQueryString } from '../../utils'import axios from 'axios'export const fetchListAction = {    fetchList ({ commit, state }, param) {        commit(FETCH_LIST_REQUEST)        axios.get('http://youdomain.com/list')          .then(function (response) {            commit(FETCH_LIST_SUCCESS, {                data: response.data            })              console.log(response);          })          .catch(function (error) {            commit(FETCH_LIST_FAILURE, {                error: error            })            console.log(error);          });    }}

getters/aGetter.js

export const = fetchListGetter = {    hotList (state) {        return state.list.data.slice(0, 10)    }}

mutations/aMutation.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from  '../constants/types'export const fetchListMutation = {    [FETCH_LIST_REQUEST] (state) {        state.isFetching = true    },    [FETCH_LIST_SUCCESS] (state, action) {        state.isFetching = false        state.data = action.data        state.lastUpdated = (new Date()).getTime()    },    [FETCH_LIST_FAILURE] (state, action) {        state.isFetching = false        state.error = action.error    }}

modules/aModule.js

import { fetchListAction } from '../actions/aAction'import { fetchListGetter } from '../getters/aGetter'import { fetchListMutation } from '../mutations/aMutation'export const list = {    state: {        isFetching: false,        data: []    }    actions: fetchListAction,    getters: fetchListGetter,    mutations: fetchListMutation}

modules/index.js

import { list } from './aModule'module.exports = {    list: list}

3. 掛載store

index.js

import Vue from 'vue'import Vuex from 'vuex'import createLogger from 'vuex/dist/logger'import { list } from './modules'Vue.use(Vuex)const store = new Vuex.Store({  modules: {    list: list      },  plugins: [createLogger()],  strict: process.env.NODE_ENV !== 'production'})if (module.hot) {  module.hot.accept(['./modules'], () => {    const newMutations = require('./modules').default    store.hotUpdate({      mutations: newMutations    })  })}export default store

4. store注入vue實例

main.js

  ····import store from './store'  ···· var vue = new Vue({  store,   ···· })vue.$mount('#app')

5. 在Component中使用

Vuex 提供了組件中使用的mapState,mapAction,mapGetter方法,因此可以很方便的調用。

Example.vue

<template> ·········</template><script>import { mapState, mapActions, mapGetters } from 'vuex'module.exports = {    ·······    methods: {        ...mapActions([            'fetchList'        ])    },    computed: {        ...mapState{            list: state => state.list        },        ...mapGetters{[            'hotList'        ]}    }}</script><style>    ·······</style>

復用模塊

模塊化拆分之后可以實現較為復雜的數據流,特別地,如果對action和mutation稍加改造,就可以復用模塊:
比如我們在Example.vue中發起Action:

Example.vue

<template> ·········</template><script>import { mapState, mapActions, mapGetters } from 'vuex'module.exports = {    ·······    mounted () {        this.fetchList({            request: 'week'        })    },    methods: {        ...mapActions([            'fetchList'        ])    },    computed: {        ...mapState{            list: state => state.list        },        ...mapGetters{[            'hotList'        ]}    }}</script><style>    ·······</style>

在上面的例子中,我們在組件掛載完成之后發起了一個fetchList的action,并添加了一個名為request的參數,這里給一個week值,也可以給按照業務需要給monthyear之類的值,接下來對aAction.js做一些修改。

actions/aAction.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from  '../constants/types'import { toQueryString } from '../../utils'import axios from 'axios'export const fetchListAction = {    fetchList ({ commit, state }, param) {        commit(FETCH_LIST_REQUEST, {            request: param['request']        })        axios.get(`http://youdomain.com/${param['request']}list`)          .then(function (response) {            commit(FETCH_LIST_SUCCESS, {                request: param['request']                data: response.data            })              console.log(response);          })          .catch(function (error) {            commit(FETCH_LIST_FAILURE, {                request: param['request']                error: error            })            console.log(error);          });    }}

請求成功之后,在 commit()中加入了一個request的參數,這樣Mutation就可以從里面獲取相應的參數,最后對aMutation做一些修改。

mutations/aMutation.js

import { FETCH_LIST_REQUEST, FETCH_LIST_SUCCESS, FETCH_LISR_FAILURE } from  '../constants/types'export const fetchListMutation = {    [FETCH_LIST_REQUEST] (state, action) {        state[action.request].isFetching = true    },    [FETCH_LIST_SUCCESS] (state, action) {        state[action.request].isFetching = false        state[action.request].data = action.data        state[action.request].lastUpdated = (new Date()).getTime()    },    [FETCH_LIST_FAILURE] (state, action) {        state[action.request].isFetching = false        state[action.request].error = action.error    }}

state加入了[action.request],以區分不同的接口數據。

完成以上修改后,只需要在組件調用相應的action時加入不同的參數,就可以調用相同類型但數據不同的接口。

總結

以上是我在Vuex實踐中總結的一些東西,分享給大家,如果有不合理或者錯誤?的地方,也希望各位老司機不吝賜教????,有機會多交流。

微信號:pasturn
Github:https://github.com/pasturn

本站僅提供存儲服務,所有內容均由用戶發布,如發現有害或侵權內容,請點擊舉報
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
成功使用vue store存取全局變量
詳講:vue2+vuex+axios
大型Vuex應用程序的目錄結構 | Fundebug博客
Vue2.0總結
kbone 高級 - 跨頁面通信和跨頁面數據共享
記一次Vue Hybrid App(混合APP)開發
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯系客服!

聯系客服

主站蜘蛛池模板: 临清市| 衡水市| 安多县| 宝丰县| 内江市| 精河县| 田阳县| 福建省| 剑阁县| 孟村| 南平市| 洪雅县| 丰原市| 洮南市| 英山县| 雷山县| 阿拉尔市| 开原市| 漯河市| 大邑县| 麻江县| 疏附县| 新巴尔虎右旗| 稷山县| 宿松县| 清流县| 金溪县| 宁化县| 北京市| 叶城县| 桂阳县| 宁乡县| 栾川县| 海伦市| 大安市| 澄城县| 洛隆县| 修文县| 陆川县| 宿州市| 鹤岗市|