vue3 全局变量
时间: 2023-06-29 13:11:07 浏览: 148
在 Vue 3 中,你可以使用 `createApp` 函数来创建一个应用实例,并在该实例中创建全局变量。具体的步骤如下:
1. 在你的入口文件中创建一个应用实例,并将其赋值给一个全局变量:
```
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 将应用实例赋值给全局变量
window.app = app
```
2. 在需要使用全局变量的组件中,在 `setup` 函数中使用 `inject` 函数引入该变量:
```
import { inject } from 'vue'
export default {
setup() {
const app = inject('app')
// 在此处可以使用全局变量 app
}
}
```
通过这种方式,你就可以在 Vue 3 中创建全局变量了。需要注意的是,全局变量的使用应该尽量避免,因为它们会增加应用的复杂度和耦合度。如果可能的话,应该尽量使用组件之间的 props 传递数据。
相关问题
uniapp vue3 全局变量
在uni-app中实现全局变量有三种方式:
第一种方式是在需要的vue文件中import公共模块,并在data中定义全局变量。然后通过调用公共模块中的变量来获取全局变量的值。示例代码如下:
```vue
<template>
<div>
<h1>{{ global_serverUrl }}</h1>
<button @click="getGlobal()">获取全局变量</button>
</div>
</template>
<script>
import common from '../common/common.js';
export default {
data() {
return {
global_serverUrl: ""
};
},
methods: {
getGlobal() {
this.global_serverUrl = common.serverUrl;
}
}
};
</script>
```
第二种方式是使用Vue.prototype挂载全局变量,直接使用this调用。在vue页面中使用全局变量时,通过this访问全局变量。示例代码如下:
```vue
<template>
<div>
<h1>{{ global_serverUrl }}</h1>
<button @click="getGlobal()">获取全局变量</button>
</div>
</template>
<script>
import common from '../common/common.js';
export default {
data() {
return {
global_serverUrl: ""
};
},
methods: {
getGlobal() {
this.global_serverUrl = this.Global_serverUrl_prototype;
}
}
};
</script>
```
第三种方式是使用vuex的store仓库来管理全局变量。在vuex的store中定义全局变量,并在需要的vue文件中通过this.$store访问全局变量。示例代码如下:
```vue
<template>
<div>
<h1>{{ global_serverUrl }}</h1>
<button @click="getGlobal()">获取全局变量</button>
</div>
</template>
<script>
export default {
data() {
return {
global_serverUrl: ""
};
},
methods: {
getGlobal() {
this.global_serverUrl = this.$store.state.global_serverUrl;
}
}
};
</script>
```
uniapp vue3全局变量
在Uniapp中设置全局变量的方法如下[^1]:
1. 在App.vue中定义全局变量:
```javascript
export default {
globalData: {
db_picture: 'https://testimg.xxxxx.com/',
uploadUrl: 'https://test.xxxxx.com',
userName: '白居易'
},
onLaunch() {
console.log(this.$scope.globalData.userName);
}
}
```
在App.vue中的`globalData`对象中定义了全局变量`userName`,可以在整个应用中访问。
2. 在其他页面中使用全局变量:
```vue
<template>
<view>
<!-- 注意,不能在模板中直接使用 getApp().globalData.userName -->
<<琵琶行>>的作者是:{{author}}
</view>
</template>
<script>
export default {
data() {
return {
author: ''
}
},
onShow() {
// 每次A.vue出现在屏幕上时,都会触发onShow,从而更新author值
this.author = getApp().globalData.userName;
}
}
</script>
```
通过在其他页面的`onShow`生命周期函数中,使用`getApp().globalData.userName`来获取全局变量的值,并将其赋给页面中的数据属性`author`,从而在模板中显示全局变量的值。
阅读全文
相关推荐
















