Appearance

全局变量

在uni 项目中全局变量有 多方法,自定义全局变量,绑定在 globalDataVue.prototype 上,以及 Vuex,这里我们主要用 Vuex,并且在vuex 里做变量持久化。

Vue.prototype

这里 我们将全局方法绑定在 Vue.prototype 上,在 .vue 文件中,我们方便直接 通过 this 指针调用。

@extends/vue.extend.js

import tools from "./tools";
import bus from "./bus.js"
import http from './request/interceptor'
import mixin from './mixin.js'
import pop from './pop.js'
import ajax from './ajax.js'
import url from '@/api/url'
import api from '@/api'
import vuexStore from '@/store/$u.mixin.js';
import {getParent,getChildren} from './getNode';
import rules,{markRule,bindRule} from "./rules";

export default {
  install: (Vue, vm) => {
	// Vue.use(soComponents);
	Vue.mixin(mixin);
	Vue.prototype.$setVuex = (name, value) => {//提供vuex 根 $setVuex方法
		vm.$store.commit('$setState', {
			name,value
		})
	}
	
	Vue.prototype.$getParent = getParent;//获取父方法
	Vue.prototype.$getChildren= getChildren;//获取子集合方法
	
	Vue.prototype.$bus = bus;//bus
	Vue.prototype.$pop = pop;//pop弹窗
	Vue.prototype.$link = vm.$u.route; //路由方法
	
	Vue.prototype.$http = http; // 基础包装的http
	Vue.prototype.$ajax = ajax; // 包装异步请求
	
    Vue.prototype.$t = tools;//工具集合
	
    Vue.prototype.$url = url;//url
    Vue.prototype.$api = api;//所有公共请求
	
    Vue.prototype.$r = rules;//所有验证规则
    Vue.prototype.$markRule = markRule;//快速生成验证
	Vue.prototype.$bindRule = bindRule;//绑定验证方法
	
	Vue.prototype.$sys = uni.getSystemInfoSync;//获取系统信息(同步方法)
	Vue.prototype.$sysInfo = uni.getSystemInfo;//获取系统信息
	Vue.prototype.$resize = uni.onWindowResize;//屏幕变化函数

  }
}

vuex 全局变量

约定变量

我们可以通过 vuex 可以在 js 和多个页面文件中公用变量,我们约定页面中需要公用的变量以 vuex_开头,如。

const store = new Vuex.Store({
	...
	state: {
		vuex_isHome : false,
		vuex_reftNav: [],
		vuex_NavCur : 'userList',
		...
	},
	...
});

获取变量

Vuex 的根 state 中的变量,我们直接通过 mixin 直接混入到了 vue组件中的data中。所以,在组件中我们可以直接通过 this 来直接访问到 这些全局变量。这样方便,但在命名上也需要我们注意这种变量的规范定义。

this.regionList = this.vuex_dict.region;

设置变量

设置 vuex 全局变量,我们可以通过快捷方法 this.$setVuex 直接设置,如:

this.$setVuex('vuex_token','isNotEmpty');

永久性变量

vuex 中需要保存到 storage 中的变量,可以将 state里已定义过的变量,在写在 @store/index.jssaveStateKeys 数组中,文件里已做简单处理,可永久性存储。

全局监听

uni 官方 提供了 全局发布订阅的方法 uni.$onuni.$onceuni.$emituni.$off 方法来实现全局监听。详情可查看官方页面通讯说明open in new window