首页 > 解决方案 > Vue 3 组合 API 和对 Vue 实例的访问

问题描述

main.js我有这样的事情:

import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });

通过这种方式,我可以访问myUtilFunc整个应用程序this.$myUtilFunc

setup()但是,如果我无法访问 Vue 3中的方法,我该如何实现this呢?

标签: javascriptvue.jsvue-componentvuejs3vue-composition-api

解决方案


使用provide/inject

提供

const app = createApp(App);
app.provide('someVarName', someVar);  // `Provide` a variable to all components here

注入

// In *any* component
const { inject } = Vue;
...
setup() {
  const someVar = inject('someVarName');   // injecting variable in setup
}

请注意,您不必从应用根目录提供,也可以provide从任何组件仅提供其子组件:

// In *any* component
setup() {
  ...
},
provide() {
  return {
    someVarName: someVar
  }
}

原始答案

[编辑:虽然我在下面的原始答案对属性仍然有用context,但不再建议使用,指南context.root中不再提及并且可能很快就会被弃用。]

在 Vue 3 中,setup有一个可选的第二个参数用于context. 您可以通过以下方式访问 Vuecontext.root实例this

setup(props, context) {
  context.root.$myUtilFunc  // same as `this.$myUtilFunc` in Vue 2
}

您可以通过以下方式访问的内容context

context.attrs
context.slots
context.parent
context.root
context.emit

推荐阅读