Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings
vuejs

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

全局属性怎么在setup中使用#14171

Discussion options

app.config.globalProperties.msg = 'hello'
export default {
mounted() {
console.log(this.msg) // 'hello'
}
}
怎么在<script setup><script>中使用这个全局变量,感觉组件式没有特别好在script 中获取全局变量的便捷模式,这个全局变量在template的说能够使用的,只能用window.msg在main.js进行注册使用吗?

You must be logged in to vote
<script setup>import { ref, getCurrentInstance } from 'vue'const instance = getCurrentInstance()console.log(instance.appContext.config.globalProperties)const msg = ref('Hello World!')</script><template>  <h1>{{ msg }}</h1>  <input v-model="msg" /></template>

Replies: 1 comment 2 replies

Comment options

<script setup>import { ref, getCurrentInstance } from 'vue'const instance = getCurrentInstance()console.log(instance.appContext.config.globalProperties)const msg = ref('Hello World!')</script><template>  <h1>{{ msg }}</h1>  <input v-model="msg" /></template>
You must be logged in to vote
2 replies
@baiwusanyu-c
Comment options

Actually, globalProperties is a compatibility API, and I don't recommend using it. As you said, you can set global variables through the window, but you can write a hook function or use a library like Pinia to manage your global state and global variables.

@baiwusanyu-c
Comment options

Another point worth mentioning is thatgetCurrentInstance was a public API provided in earlier versions. It was used to retrieve the current component instance, which in turn allowed access to the app context. However, due to stability considerations, this API is no longer publicly available and is no longer mentioned in the official documentation. Therefore, I strongly recommend that if you are usingsetup to write Vue components, you can use other methods to set global variables;globalProperties is not mandatory.

Answer selected bybaiwusanyu-c
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
None yet
2 participants
@holly9715@baiwusanyu-c

[8]ページ先頭

©2009-2025 Movatter.jp