在main.js 注册全局组件(prototype)可以访问的属性
vue2.0
Vue.prototype.$Msg = (info, msgType) => {
ElMessage ({ message: info, type: msgType, customClass: 'm-z-index' })
}
vue3.0
const app = createApp(App)
app.config.globalProperties.$Msg = (info, msgType) => {
ElMessage ({ message: info, type: msgType, customClass: 'm-z-index' })
}
在vue中使用 msg全局属性
vue2.0
this.$Msg('提示内容','error')
vue3.0
在vue3.0 setup无法使用this(setup 是vue还没有创建前就执行的所以无法使用this)
import {reactive,toRefs,getCurrentInstance } from 'vue'
setup(){
const { proxy } = getCurrentInstance();
proxy 就是组件实例化对象
proxy.$Msg(‘提示内容’, 'error');
}
本文详细介绍了如何在Vue 2.0和Vue 3.0中注册全局组件,特别是如何创建并使用名为$Msg的全局属性来显示消息提示。在Vue 2.0中,通过Vue.prototype扩展原型链实现;而在Vue 3.0中,利用createApp的config.globalProperties进行设置。同时,针对Vue 3.0的setup语法特性,展示了如何在setup函数内部通过getCurrentInstance获取proxy来调用全局属性。

1358

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



