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 实例的访问
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
