Skip to content

前言:

vue3.0中的全局定义属性值和2.0是不一样的,是使用了globalProperties,而且跟我们2.0中可以用 this.+我们挂载的属性名 的用法相比,我们3.0的使用 方法是不一样的,这里总结下

一、vue2.0

1、main.js中

java
import api from './api' // 导入api接口
Vue.prototype.$api = api
Vue.prototype.$abc = 111

2、.vue中:

java
this.$api.user...

let abc = this.$abc   //111

二、vue3.0

1、main.js中

java
const app = createApp(App)
//全局配置
app.config.globalProperties.foo = 'bar'

2、.vue中:

2.1 选项式api:mounted中(和2.0中用法一样)

但是3.0中很少使用mounted

java
let abc = this.foo //bar

2.2 组合式api:setup中 (重头戏)

(1)使用 ctx (强烈不推荐!)

js
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();

经过测试,打包到dist以后,ctx下面的值是拿不到的,本地可以!

==(2)使用 proxy (强烈推荐)==

java
setup() {
     const { proxy, ctx } = getCurrentInstance()
     const showMessage = () => {
      let m = proxy.foo 
      let n = ctx.foo
      ElMessage.success({
        message: 'proxy: '+m, //本地和打包出来都可以拿到
        type: 'success'
      })
      ElNotification({
        title: 'ctx: '+n, //打包出来以后,内容拿不到
      })
    }
    return {
      showMessage
    }
}

==(3)使用 appContext.config.globalProperties,也比较推荐==

appContext.config.globalProperties = proxy

js
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const globalProperties = appContext.config.globalProperties

console.log(globalProperties.foo)

本地debugger查看配图:

proxy

image-20221201162520414

ctx

image-20221201162527014

三、官方解释

入口:https://cn.vuejs.org/api/application.html#app-config

globalProperties

  • 类型:[key: string]: any
  • 默认:undefined
  • 用法:
js
app.config.globalProperties.foo = ‘bar’
app.component(‘child-component’, {
    mounted() {
    console.log(this.foo) // ‘bar’
    }
})

添加可以在应用程序内的任何组件实例中访问的全局 property。属性名冲突时,组件的 property 将具有优先权。

这可以代替 Vue 2.x

Vue.prototype扩展:

java
// 之前(Vue 2.x)
Vue.prototype.$http = () => {}

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

实际应用:(爱旅游)

image-20230404140519401image-20230404140501519