zoukankan      html  css  js  c++  java
  • 从0开始探究vue-公共变量的管理

    背景

    Vue项目中,我们总会遇到一些公共数据的处理,如方法拦截,全局变量等,本文旨在解决这些问题

    解决方案

    事件总线

    所谓事件总线,就是在当前的Vue实例之外,再创建一个Vue实例来专门进行变量传递,事件处理,管理回调事件等

    //main.js中
    Vue.prototype.$bus = new Vue();
    new Vue({...})
    
    //页面一
    this.$bus.$on('sayName',(e)=>{
        alert('我的名字是',e)
    })
    
    //页面二
    this.$bus.$emit('sayName','小明');//我的名字是 小明
    

    原型挂载

    所谓原型挂载,就是在main.js中将公共变量,事件,都挂在到Vue原型上

    //main.js
    Vue.prototype.$globalData = {}
    Vue.prototype.$sayName = function(e){
        console.log('我的名字是',e)
    }
    new Vue({...})
    
    //组件一
    Vue.prototype.$globalData.name='小明';
    this.$sayName('小王');//我的名字是小王
    
    //组件二
    console.log(this.$sayName.name);//小明
    this.$sayName('小王');//我的名字是小王
    
    

    vuex

    VuexVue提供的一种,专门用来管理vue中的公共状态,事件等等,以应用登录为例

    //新建store.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    import axios from 'axios'
    Vue.use(Vuex)
    export default new Vuex.Store({
      state: {//此处为公共变量
        userId:"",//用户Id
        loginSession:""//用户登录凭证
      },
      mutations: {//此处为同步方法
        setLoginSession(state,loginSession){//存入state中的用户凭证
            state.loginSession = loginSession;
        },
        setUserId(state,loginSession){//存入state中的用户凭证
            state.loginSession = 'user_'+Math.floor(Math.random()*100000000000);
        }
      },
      actions: {//此处为异步方法
        getUserId({state,commit},options={}){//从服务器取登录凭证,然后返回是否登录状态
            return new Proise((resolve)=>{//返回一个promise对象,来让调用者可以使用.then来进行下一步操作
                axios.get('api').then((res)=>{
                    commit('setLoginSession',res.data.loginSession)
                    resolve(this.getters.isLogin)
                })
            }))
        }
      },
      modules: {//此处为混入更多的vuex小模块
        
      },
      gatters: {//此处为计算变量
          isLogin(){
              return (this.userId&&this.loginSession)?true:false
          }
      }
    })
    //main.js中注入vuex
    import store from './store/store.js'
    Vue.prototype.$store = store;
    
    //app.vue中
    export default {
        data(){
            return {}
        },
        mounted(){
            this.$store.commit('setUserId');//设置用户Id
            this.$store.dispatch('getUserId').then((result)=>{//查询登录凭证,并返回登录结果
                console.log(this.$store.getters.isLogin,result);//true  true  此处也可以查看计算属性中的是否登录状态
                if(result){
                    alert('登录了')
                }else{
                    alert('未登录')
                }
            });
        }
    }
    
  • 相关阅读:
    TSQL 错误状态
    CSS光标聚焦改指针为手
    PD使用指导
    Ext 为label添加单击事件
    (转) SQL Server中解决死锁的新方法介绍
    DateTime 的使用技巧
    (转) C# 接口
    常见频率f与周期T之间的关系
    上拉电阻与下拉电阻的作用和区别
    powershell命令返回值
  • 原文地址:https://www.cnblogs.com/mr-xiao-han/p/12389953.html
Copyright © 2011-2022 走看看