目前看到三种方式
1.共用模块
定义一个专用的摩卡,用来组织和管理这些全局的变量,在需要用到的页面导入
如下:
创建一个helper.js
const token = 'asdafqwdsda’;
function doSomeThing (thing) {
console.log('一个后空翻之后又'+thing);
}
//导出
export default {
token,
doSomeThing,
}
在需要用到的地方导入
// 对应如下导入
import helper from '@/common/helper.js';
console.log(helper.token);
helper.doSomeThing(‘啊哈哈哈’);
2.挂载Vue.prototype
将一些使用频率高的常量或方法直接挂载到Vue.prototype上,每个vue对象都会继承下来
如下:
在main.js中挂载属性、方法
Vue.prototype.$realName = '大哥飞';
Vue.prototype.$eat = function (name) {
console.log(name + '顺便吃了个饭');
}
3.globalData
在App.vue中可以定义globalData
如下:
<script>
export default {
globalData: {
loginInfo: {}
},
onLaunch: function() {
console.log('App Launch')
this.globalData.loginInfo = {userName:'Lange',age:'11',gender:'男'};
},
}
</script>
在需要用的地方直接调用即可
console.log(getApp().globalData.loginInfo);