Vue 3 composition API and access to Vue instance(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 实例的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vue 3 组合 API 和对 Vue 实例的访问


基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01