zoukankan      html  css  js  c++  java
  • vue项目实战:vuex板块的考虑和封装

    个人比较推荐用模块方式管理各个模块需要用到的vuex公共数据  当然你可以依据你自己喜欢的方法方式进行管理

    /*
     * @Description: vuex入口  store/index
     * @Version: 2.0
     * @Autor: lhl
     * @Date: 2020-07-08 09:16:36
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-20 17:23:03
     */ 
    
    import Vue from 'vue'
    import Vuex from 'vuex'
    import createRenderer from 'vuex/dist/logger'
    // import commonInfo from './modules/commonInfo' 普通模式导入每个模块
    
    Vue.use(Vuex)
    
    // 官方动态加载所有模块
    function loadModules() {
      const context = require.context("./modules", false, /([a-z_]+).js$/i);
      const modules = context
        .keys()
        .map((key) => ({ key, name: key.match(/([a-z_]+).js$/i)[1] }))
        .reduce(
          (modules, { key, name }) => ({
            ...modules,
            [name]: context(key).default
          }),
          {}
        )
      return { context, modules }
    }
    
    const { context, modules } = loadModules();
    
    const debug = process.env.NODE_DEV !== 'production'
    
    export default new Vuex.Store({
      // 动态导入模式
      modules,
      // 普通模式
      // modules:{
      //   commonInfo
      // },
      strict: debug,
      plugins: debug ? [createRenderer()] : [] // 断点
    })
    
    // 如果你仅使用模块,你可以使用 require.context 来动态地加载或热重载所有的模块 动态模块热重载
    // 官方链接 ctrl + 鼠标左键即可查看官方文档 https://vuex.vuejs.org/zh/guide/hot-reload.html#%E5%8A%A8%E6%80%81%E6%A8%A1%E5%9D%97%E7%83%AD%E9%87%8D%E8%BD%BD
    if (module.hot) {
      // 在任何模块发生改变时进行热重载。
      module.hot.accept(context.id, () => {
        const { modules } = loadModules()
        store.hotUpdate({
          modules
        })
      })
    }
    /*
     * @Description: 公共的信息  import { mapActions, mapGetters, mapMutations } from "vuex"; store/modules/commonInfo.js
     * @Version: 2.0 
     * @Autor: lhl
     * @Date: 2020-07-08 09:17:55
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-20 17:24:04
     */ 
    export default {
      // 初始化数据(当做项目公共数据----粗俗点就是js全局变量)
      state: {
        contentBoxHeight: (window.innerHeight - 80), //动态计算右侧内容总高度
        testContent: '测试vuex存储数据的功能',
        count: 0
      },
      mutations: {
        // 只能同步操作
        // 设置右侧内容动态高度
        setContentBoxHeight(state, num) {
          state.contentBoxHeight = num;
        },
        changeTestContent(state, content){
          state.testContent = content;
        },
        // +
        add(state, n){
          state.count += n;
        },
        // -
        reduce(state, n){
          state.count -= n;
        },
      },
      getters: {
        getTestContent: state => state.testContent,
        getCount: state => state.count,
        getcontentBoxHeight: state => state.contentBoxHeight,
      },
      actions:{
        // 可以异步操作
        add({ commit },count){
          setTimeout(() => {
            commit('add',count)
          },1000)
        },
        // - 
        reduce({ commit },count){
          setTimeout(() => {
            commit('reduce',count)
          },3000)
        },
      }
    }
    
    /*
    // 组件使用 mutations 同步操作  actions 异步操作[如:ajax,setTimeout、Promise等]
    import { mapState,mapGetters,mapMutations,mapActions } from 'vuex';
    // 在computed中使用
    ...mapState({
      contentBoxHeight: state => state.commonInfo.contentBoxHeight
    })
    
    ...mapGetters(['xxx'])
    
    // 在methods中使用 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
    ...mapMutations(['xxx']) <===> this.$store.commit('方法名',传参)" [组件内使用] <===> js中使用 store.commit('方法名',传参)  <===> dom使用 @click="xxx(参数)" 
    
    // Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作 一个 store.dispatch 在不同模块中可以触发多个 action 函数
    ...mapActions(['xxx']) <===> this.$store.dispatch('方法名',传参)" [组件内使用] <===> js中使用 store.dispatch('方法名',传参)  <===> dom使用 @click="xxx(参数)" 
    
    // 推荐使用对象风格的提交方式
    store.commit({
      type: '方法名',
      参数名: 值
    })
    
    store.dispatch({
      type: '方法名',
      参数名: 值
    })
    
    当需要在对象上添加新属性时 Vue.set(对象, '新属性', 值)   新对象替换老对象 state.obj = { ...state.obj, 新属性: 值 }
    */
    /*
     * @Description: 用户信息 localStorage  sessionStorage存储token  打开新窗口会导致再次登录  或者使用 js-cookie 插件处理  import Cookies from 'js-cookie'  store/modules/user.js
     * @Version: 2.0
     * @Autor: lhl
     * @Date: 2020-08-03 17:47:28
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-20 17:24:14
     */
    // const uToken = 'Admin-Token'
    
    // export function getToken(uToken) {
    //   return Cookies.get(uToken)
    // }
    
    // export function setToken(uToken,token) {
    //   return Cookies.set(uToken, token)
    // }
    
    // export function removeToken(uToken) {
    //   return Cookies.remove(uToken)
    // }
     export default {
       state:{
        userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}, 
        token: localStorage.getItem('uToken') ? localStorage.getItem('uToken') : "",
        btnCodeList: localStorage.getItem('btnCodeList') ? JSON.parse(localStorage.getItem('btnCodeList')) : [],
       },
       mutations:{
        setToken(state,token){
          state.token = token;
          localStorage.setItem('uToken', token);
        },
        setUserInfo(state,userInfo){
          state.userInfo = userInfo;
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
        },
        setBtnPermitCode(state,btnCodeList){
          state.btnCodeList = btnCodeList;
          localStorage.setItem('btnCodeList', JSON.stringify(btnCodeList));
        },
        loginOut(){
          localStorage.clear();
          setTimeout(() => {
            location.reload();
          }, 500)
        }
       },
       getters:{
         getToken: state => state.token,
         getUserInfo: state => state.userInfo,
         getBtnCodeList:  state => state.btnCodeList
       }
     }

      以上代码本人项目实测!!!真实可靠,请勿随意转载~转载请注明出处~~~谢谢合作!

  • 相关阅读:
    【转】探秘Java中的String、StringBuilder以及StringBuffer
    【转】深入剖析Java中的装箱和拆箱
    谈谈我对多态的理解
    mysql组合索引之最左原则
    白衣浅谈各个集合的特性
    Linux 下的两个特殊的文件 -- /dev/null 和 /dev/zero 简介及对比
    内网穿透工具的原理与开发实战
    nohup命令说明-转载
    springboot 启动jar正确方式
    maven版本仲裁原则
  • 原文地址:https://www.cnblogs.com/lhl66/p/13536320.html
Copyright © 2011-2022 走看看