In vue2, we know that vue2.x uses Vue.prototype.$xxxx=xxx to define global variables, and then obtains global variables through this.$xxx.
But in vue3, this method obviously does not work. Because we cannot get this in setup in vue3, so according to the official documentation we use the following method to define global variables:
First write a global variable we want to define in main.js, such as a System id
app.config.globalProperties.$systemId = "10"
Now you need to use this variable in the page. You only need to introduce getCurrentInstance from vue. Note that you cannot use this.
import { getCurrentInstance } from "vue"; const systemId = getCurrentInstance()?.appContext.config.globalProperties.$systemId console.log(systemId);//控制台可以看到输出了10
Type: [key: string]: any
// 之前(Vue 2.x) Vue.prototype.$http = () => {} // 之后(Vue 3.x) const app = Vue.createApp({}) app.config.globalProperties.$http = () => {}
import { getCurrentInstance, onMounted } from "vue"; export default { setup( ) { const { ctx } = getCurrentInstance(); //获取上下文实例,ctx=vue2的this onMounted(() => { console.log(ctx, "ctx"); ctx.http(); }); }, };
import { getCurrentInstance } from 'vue' export default ({ name: '', setup(){ const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因为ctx只在开发环境有效 onMounted(() => { console.log(proxy, "proxy"); proxy.http(); }); } })
The above is the detailed content of How to define global variables in vue3. For more information, please follow other related articles on the PHP Chinese website!