main.js年里,我有这样的东西:

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

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

但是,如果我没有this的访问权限,我如何在Vue 3中实现同样的setup()分制方法呢?

推荐答案

Use provide/inject

Provide

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

Inject:

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

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

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

原始答案

[103: While my original answer below is still useful for 101 properties, it's no longer recommended to use 102, which is no longer mentioned in the 100 and may soon be deprecated.]

在Vue 3中,setup有一个可选的context的第二个参数.您可以通过context.root而不是this访问Vue实例:

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

您可以通过context访问的内容:

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

Vue.js相关问答推荐

如何默认打开一个v-list-group?

我在 nuxt2 中看不到索引页

vue 不重新渲染数据更改

Vue CLI - 编译后将配置文件保留为外部

如何使用带有自定义标签和类的`transition-group`

Object.assign 没有正确复制

Vue:限制文本区域输入中的字符,截断过滤器?

在 vue.js 中获取当前时间和日期

Vue 3 如何获取有关 $children 的信息

使用 azure devops 发布管道部署 Vue.js 应用程序

Vue test-utils 如何测试 router.push()

SVG 加载 vue-svg-loader; [Vue 警告]:无效的组件定义

在组件之间共享数据

如何将项目推送到 Vuejs 中数据对象的数组中? Vue 似乎没有关注 .push() 方法

[Vue 警告]:无效的props:propsscrollThreshold的类型判断失败.期望的数字,得到字符串

使用props向组件添加类名

按键删除对象不会更新vue组件

使用 Vue.js & DataTable(jquery 插件)

Vue.js 的 $emit 和 $dispatch 有什么区别?

Vuetify 离线文档