概述|Overview
在 #Vue 2 中,可以通过多种方式定义 #全局变量 , 以便在整个应用程序中共享数据和功能
方法一 和 方法二 适用于需要在所有组件中使用全局方法的情况。
方法三 适用于需要在父组件中引用子组件实例并访问其数据和方法的情况。
环境|Environment
名称 |
版本 |
备注 |
Windows |
10 home x64 |
|
Vue |
2 |
|
方法一 直接写在 main.js + Vue.prototype 挂载
main.js
1
2
|
// 自定义常量
Vue.prototype.$JOB_TYPE_DEVELOPER = '2'
|
user.vue
1
2
3
4
5
6
7
|
jobNameFormatter(row, cellValue) {
if (row.jobType === this.$JOB_TYPE_DEVELOPER) {
return ' ' + row.jobName
} else {
return row.jobName
}
}
|
方法二 exports 暴露 + main.js 引用 + Vue.prototype 挂载
写好自己需要的 use.js
文件,通过 exports
暴露
1
2
3
4
5
|
export function use(Vue, options) {
Vue.prototype.$getToken = function (){
...
};
};
|
main.js 引入并使用
1
2
3
4
|
import Vue from 'vue';
import { use } from './use';
Vue.use(use);
|
通过 this.$getToken()
在所有组件里可调用函数
方法三 定义全局使用的 vue
组件 Global.vue
+ 父子组件的方式ref使用
编写全局使用的 vue
组件 Global.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<script>
export default {
data() {
return {
token: 'xxx'
};
},
methods: {
getToken() {
// 实现你的逻辑
}
}
};
</script>
|
你可以使用 ref
来引用子组件实例,并在 mounted
钩子中访问它。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<template>
<div>
<Global ref="globalComponent" />
</div>
</template>
<script>
import Global from '../../components/Global';
export default {
components: {
Global
},
mounted() {
// 访问子组件实例并调用其方法
this.$refs.globalComponent.getToken();
}
};
</script>
|
未来展望|Further
参考|References
- Vue中定义全局可以使用的变量和方法
- Vue.js项目中全面解析定义全局变量的常用方法与技巧