Home  >  Article  >  Web Front-end  >  How to define global variables in vue3

How to define global variables in vue3

PHPz
PHPzforward
2023-05-12 16:40:147544browse

vue3 defines global variables

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

vue3 global variable app.config in the page. Usage of .globalProperties

globalProperties

  • Type: [key: string]: any

  • ##Default: undefined

  • Usage

Add a global property that can be accessed in any component instance of the application. Component properties take precedence in naming conflicts.

This can replace the Vue 2.x Vue.prototype extension:

// 之前(Vue 2.x)
Vue.prototype.$http = () => {}
 
// 之后(Vue 3.x)
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

When we want to call http within the component, we need to use getCurrentInstance() to obtain it.

import { getCurrentInstance, onMounted } from "vue";
export default {
  setup( ) {
    const { ctx } = getCurrentInstance(); //获取上下文实例,ctx=vue2的this
    onMounted(() => {
      console.log(ctx, "ctx");
      ctx.http();
    });
  },
};

getCurrentInstance represents the context, that is, the current instance. ctx is equivalent to this of Vue2, but it is important to note that ctx instead of this is only suitable for the development stage. If the project is packaged and run on the production server, an error will occur. ctx cannot obtain routing and global mounting objects. The solution to this problem is to use proxy instead of ctx. The code reference is as follows.

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete