在main.js
年里,我有这样的东西:
import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });
通过这种方式,我可以用this.$myUtilFunc
访问整个应用程序中的myUtilFunc
但是,如果我没有this
的访问权限,我如何在Vue 3中实现同样的setup()
分制方法呢?
在main.js
年里,我有这样的东西:
import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });
通过这种方式,我可以用this.$myUtilFunc
访问整个应用程序中的myUtilFunc
但是,如果我没有this
的访问权限,我如何在Vue 3中实现同样的setup()
分制方法呢?
provide
/inject
Provide
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
}
}
[103: While my original answer below is still useful for 101 properties, it's no longer recommended to use 102, which is no longer mentioned in the 100 and may soon be deprecated.]
在Vue 3中,setup
有一个可选的context
的第二个参数.您可以通过context.root
而不是this
访问Vue实例:
setup(props, context) {
context.root.$myUtilFunc // same as `this.$myUtilFunc` in Vue 2
}
您可以通过context
访问的内容:
context.attrs
context.slots
context.parent
context.root
context.emit