前言:

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

目录:

一、2.0

main.js中

页面上:

二、3.0

main.js中

页面上:

1、mounted中 (和2.0中一样)但是3.0中很少使用mounted

2、setup (重头戏)

(1)使用 ctx ,但是经过测试,打包到dist以后,ctx下面的值是拿不到的,本地可以

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

本地debugger查看配图:

​proxy

​ctx

三、官方解释:入口

globalProperties


一、2.0

main.js中

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

页面上:

this.$api.user...

let abc = this.$abc   //111

二、3.0

main.js中

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

页面上:

1、mounted中 (和2.0中一样)但是3.0中很少使用mounted

let abc = this.foo //bar

2、setup (重头戏)

(1)使用 ctx ,但是经过测试,打包到dist以后,ctx下面的值是拿不到的,本地可以

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

 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
    }
}

本地debugger查看配图:

proxy

ctx

三、官方解释:入口

globalProperties

  • 类型[key: string]: any

  • 默认undefined

  • 用法

app.config.globalProperties.foo = 'bar'

app.component('child-component', {
  mounted() {
    console.log(this.foo) // 'bar'
  }
})

 

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

这可以代替 Vue 2.x Vue.prototype 扩展:

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

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

 

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐