在Vue
项目中,咱们总会遇到一些公共数据的处理,如方法拦截,全局变量等,本文旨在解决这些问题vue
所谓事件总线,就是在当前的Vue
实例以外,再建立一个Vue实例来专门进行变量传递,事件处理,管理回调事件等ios
//main.js中 Vue.prototype.$bus = new Vue(); new Vue({...}) //页面一 this.$bus.$on('sayName',(e)=>{ alert('个人名字是',e) }) //页面二 this.$bus.$emit('sayName','小明');//个人名字是 小明
所谓原型挂载,就是在main.js
中将公共变量,事件,都挂在到Vue原型上vuex
//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
是Vue
提供的一种,专门用来管理vue
中的公共状态,事件等等,以应用登陆为例axios
//新建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('未登陆') } }); } }