vue2.x挂载全局是使用Vue.prototype.$xxxx=xxx的形式来挂载,然后通过this.$xxx来获取挂载到全局的变量或者方法
在vue3.x这种方法显然是不行了,vue3中在setup里面我们都获取不到this,官方提供了globalProperties
import { createApp } from 'vue'
import App from './App'
import router from '@router/index'
const app = createApp(App).app.use(router).mount('#app')
app.config.globalProperties.$demoe = 'demo'
注意:千万不能这样子写:
createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com'
createApp(App).use(router)
.use(store)
.use(elementPlusUI)
.mount('#app')
//或者是这样
const app = createApp(App)
createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com'
app.use(router)
.use(store)
.use(elementPlusUI)
.mount('#app')
种相当于我们直接调用了两次createApp(App),
最后调的那次里面压根就没有我们需要配置的全局变量,会返回undefined
在 compose api 如何用?
只需要从vue引入一个方法即可,不能在页面中使用this获取
import { defineComponent, getCurrentInstance, onMounted } from "vue"
export default defineComponent({
setup (props, {emit}) {
// console.log(this)
const { appContext : { config: { globalProperties } },proxy} = getCurrentInstance()
const { ctx, proxy } = getCurrentInstance()
console.log(globalProperties.$demo)
return {
proxy
}
}
})
ctx和proxy都可以访问到定义的全局方法,但是ctx只能在本地使用,线上环境使用proxy// 来源:https://www.nzw6.com