Vue 3 全局注册属性与方法
文章目录
- Vue 3 全局注册属性与方法
- 1、在 main.ts 文件中全局注册
- 2、在组件中调用
- 3、运行结果
1、在 main.ts 文件中全局注册
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
const app = createApp(App);
// 全局注册属性
app.config.globalProperties.name = '訾博';
// 全局注册方法
app.config.globalProperties.sayHello = function () {
console.log('Hello');
}
app.mount('#app')
2、在组件中调用
<template></template>
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance();
if (instance) {
const global = instance.appContext.config.globalProperties
console.log(global.name) // 訾博
global.sayHello() // Hello
}
</script>
3、运行结果
訾博
Hello