javascript - Vue 3 组合 API 和对 Vue 实例的访问
问题描述
在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
注入:
// 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
中不再提及并且可能很快就会被弃用。]
在 Vue 3 中,setup
有一个可选的第二个参数用于context
. 您可以通过以下方式访问 Vuecontext.root
实例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
推荐阅读
- azure-functions - VS2019 Azure Function Solution组织
- c# - 一个简单类型的匿名类型属性的实例如何不总是返回相同的值?
- python - Python:将分类变量的值替换为数据框中的其他值
- sql - 一列中的多列
- python - Pandas - 从 json 文件中读取 datetime64 对象时出现问题
- reactjs - ReactJS react-show-more-text`lines`道具不起作用
- javascript - 如何使 js 生成的元素与静态 html 元素正确交互?
- reactjs - 用 Jest 模拟 React 自定义钩子
- python - 在两个条目小部件(tkinter)中一次断开多个输入
- linux - 有人可以帮我将这行代码翻译成 bash shell 吗?