globalProperties

  • 类型:[key: string]: any
  • 默认:undefined
  • 用法

添加一个可以在应用的任何组件实例中访问的全局 property。组件的 property 在命名冲突具有优先权。

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

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

当我们想在组件内调用http时需要使用getCurrentInstance()来获取。

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

getCurrentInstance代表上下文,即当前实例。ctx相当于Vue2的this, 但是需要特别注意的是ctx代替this只适用于开发阶段,如果将项目打包放到生产服务器上运行,就会出错,ctx无法获取路由和全局挂载对象的。此问题的解决方案就是使用proxy替代ctx,代码参考如下。

import { getCurrentInstance } from 'vue'
export default ({
  name: '',
  setup(){
    const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因为ctx只在开发环境有效
	onMounted(() => {
      console.log(proxy, "proxy");
      proxy.http();
    });
  }
})

注意:尤大在vue3推荐使用依赖注入:provide和inject。原因:vue/rfcs.
我们将在下篇博文介绍provide和inject .

Logo

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

更多推荐