zoukankan      html  css  js  c++  java
  • [ vue ] 解耦vuex(按照组件来组织vuex的结构)

    问题描述

    随着应用复杂度的增加,vuex用一个 store/index.js 文件来描述已经很难维护了,我们想把这些状态分割到单独文件里面。

    参考1:https://vuex.vuejs.org/zh/guide/structure.html

    参考2:https://github.com/PanJiaChen/vue-element-admin

    [ 最终项目结构 ]

    E:.
    │          
    ├─components
    │     article.vue
    │     header.vue
    │     sidebar.vue
    │     ...
    │      
    ├─router
    │      index.js
    │      
    ├─store
       │  index.js
       │  
       └─ modules
               article.js
               header.js
               sidebar.js

    解决方案

    1. article.js / header.js / sidebar.js

    注意开启了namespaced,在取的state的时候要这样写: this.$store.state.article.msg 

    const state = {
        msg:''
    }
    const mutations = {
        CHANGE_MSG:(state,val)=>{
            state.msg = val
        }
    }
    const actions = {
        change_msg(context,val){
            context.commit('CHANGE_msg',val)
        }
    }
    export default {
        namespaced: true,
        state,
        mutations,
        actions
    }

    2. index.js

      1. 注意mymodules的构成

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    const modulesFiles = require.context('./modules', true, /.js$/)
    // you do not need `import app from './modules/app'`
    // it will auto require all vuex module from modules file
    const mymodules = modulesFiles.keys().reduce((modules, modulePath) => {
      // set './app.js' => 'app'
      const moduleName = modulePath.replace(/^./(.*).w+$/, '$1')
      const value = modulesFiles(modulePath)
      modules[moduleName] = value.default
      return modules
    }, {})
    
    /**
    mymodules:{
      article:{
        namespaced:true,
        state:{},
        ...
      },
      header:{
        namespaced:true,
        state:{},
        ...
      }
    }
     */
    console.log(mymodules)
    const store =  new Vuex.Store({
        modules:mymodules
    })
    
    export default store
  • 相关阅读:
    JMeter测试WEB性能入门
    Monkey测试运用实例
    Event percentages解析
    Monkey测试结果分析
    Monkey测试环境搭建
    Appium+java移动端项目测试问题整理
    appium定位安装包启动类名称
    Appium元素定位(uiautomatorviewer)
    Appium环境搭建(Windows版)
    Selenium+java项目测试问题整理
  • 原文地址:https://www.cnblogs.com/remly/p/12674090.html
Copyright © 2011-2022 走看看