app.config.globalProperties是一个用于注册能够被应用内所有组件实例访问到的全局属性的对象。是Vue2中Vue.prototype使用的一种替代,具体用法如下:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
app.use(store).use(router).mount('#app')
app.config.globalProperties.message = 'hello'// 自定义添加
1、在组合式api使用:
<script setup>
// 通过getCurrentInstance 获取
import { getCurrentInstance, onMounted } from 'vue'
const { message } = getCurrentInstance().appContext.config.globalProperties
onMounted(() => {
console.log(message) // hello
})
</script>
2、在选项api中使用:
<script>
export default {
mounted () {
console.log(this.message) // hello
}
}
</script>
本文介绍如何在Vue3中利用app.config.globalProperties添加全局属性,并演示了在组合式API和选项API中访问这些属性的方法。
3858

被折叠的 条评论
为什么被折叠?



