vue global.vue 怎么实现全局变量
时间: 2023-07-07 19:45:27 浏览: 57
在Vue中,我们可以通过在一个单独的Vue实例中定义全局变量并在其他组件中使用来实现全局变量。
首先,在一个单独的Vue实例中定义全局变量:
```
// global.vue
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
globalVariable: 'Hello World!'
}
}
}
</script>
```
接下来,在其他组件中使用该全局变量,我们可以通过Vue的mixin混入选项来实现:
```
// otherComponent.vue
<template>
<div>{{ globalVariable }}</div>
</template>
<script>
import global from './global.vue';
export default {
mixins: [global],
// ...
}
</script>
```
这样,在otherComponent.vue组件中就可以使用global.vue中定义的全局变量了。
另外,我们也可以在Vue.prototype中挂载全局变量,这样可以在任何Vue组件中访问到该全局变量:
```
// global.js
import Vue from 'vue';
Vue.prototype.$globalVariable = 'Hello World!';
// otherComponent.vue
<template>
<div>{{ $globalVariable }}</div>
</template>
<script>
export default {
// ...
}
</script>
```
这样在其他组件中就可以通过`$globalVariable`来访问全局变量了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)