Vue 3合成API和对Vue实例的访问 [英] 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
?
推荐答案
在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屋!
查看全文