Vue 3 组合 API 和对 Vue 实例的访问 [英] Vue 3 composition API and access to Vue instance

查看:26
本文介绍了Vue 3 组合 API 和对 Vue 实例的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main.js 我有这样的东西:

In main.js I have something like this:

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

通过这种方式,我可以使用 this.$myUtilFunc

In this way I have acess to myUtilFunc across whole application with this.$myUtilFunc

但是,如果我无法访问 this,如何在 Vue 3 的 setup() 方法中实现相同的功能?

But how can I achieve the same in setup() method in Vue 3 if I don't have access to this?

推荐答案

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

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

Note that you don't have to provide from the app root, but can also provide from any component to only its sub-components:

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


原答案

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


Original answer

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

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

In Vue 3, setup has an optional second argument for context. You can access the Vue instance through context.root instead of this:

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

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

Things you can access through context:

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

这篇关于Vue 3 组合 API 和对 Vue 实例的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆