在 main.js
我有这样的事情:
import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });
这样我就可以访问
myUtilFunc
在整个应用程序中使用 this.$myUtilFunc
但是我怎样才能在
setup()
中达到同样的效果? Vue 3 中的方法,如果我无权访问 this
?
最佳答案
使用provide
/inject
提供
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
}
}
原始答案
[ 编辑 :虽然我下面的原始答案对
context
仍然有用属性,不再推荐使用context.root
,guide 中不再提及并且可能很快就会被弃用。]在 Vue 3 中,
setup
context
有一个可选的第二个参数.您可以通过 context.root
访问 Vue 实例而不是 this
:setup(props, context) {
context.root.$myUtilFunc // same as `this.$myUtilFunc` in Vue 2
}
您可以通过 context
访问的内容:context.attrs
context.slots
context.parent
context.root
context.emit
关于javascript - Vue 3 组合 API 和对 Vue 实例的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60202724/