我遇到了Vue 3(alpha 4)的问题:
在setup()
函数内部,我试图读取父组件。根据{{3}}上的文档,它应该通过context
参数公开父对象,它可以作为context.attrs的属性,也可以直接作为父对象公开(请参见“键入”下的SetupContext
位) 。对于parent
还是应该直接从SetupContext
或通过SetupContext.attrs
访问的SetupContext
来说,我的文档并不十分清楚,因此我尝试了两种方法,但都无济于事。
这是我的问题,登录日志时可以正常访问SetupContext.attrs
和SetupContext.attrs
(其中是代理)。 [[Handler]]
公开了常用的代理属性([[Target]]
,[[IsRevoked]]
和[[Target]]
),并且在检查export default {
setup(props, context) {
console.log(context);
// Output: {attrs: Proxy, slots: Proxy, emit: ƒ}
console.log(context.attrs);
// Output: Proxy {vnode: {…}, parent: {…}, appContext: {…}, type: {…}, root: {…}, …}
console.log(context.attrs.parent);
// Output: undefined
}
};
时清楚地显示了父https://vue-composition-api-rfc.netlify.com/api.html#setup。>
但是在登录父目录时,它只是打印出未定义的内容:
export default {
setup(props, { attrs, parent }) {
console.log(attrs);
// Output: Proxy {vnode: {…}, parent: {…}, appContext: {…}, type: {…}, root: {…}, …}
console.log(attrs.parent);
// Output: undefined
console.log(parent);
// Output: undefined
}
};
传播上下文会产生相同的结果:
{{1}}
我对JavaScript代理还是有点陌生,但是从我对它们的了解以及尝试使用react()返回的代理开始。我应该能够像平常使用对象一样访问属性。关于我在做什么错的任何想法吗?
我已经创建了property来重现该问题
答案 0 :(得分:0)
我知道这不能直接回答问题,但是使用provide / inject(https://v3.vuejs.org/guide/component-provide-inject.html)帮助我解决了同样的问题,我想从父节点获取数据属性并将其传递给从渲染的组件,但是从Vue2升级到Vue3后无法再访问父组件。我没有尝试公开父对象,而是将prop从其数据集中传递到了渲染的组件。
创建应用程序后,我执行了以下操作。
main.js
import { createApp } from "vue";
import MyComponent from './components/MyComponent.vue';
const section = document.getElementById('some-element'); // this element contains a data-attribute which I need to use within the app. In my case, I can't get the data from the component created/mounted function as the section with the data attribute is loaded onto the page multiple times with different attributes each time.
const app = createApp(MyComponent);
app.provide('dataset', section.dataset.id); // section.dataset.id contains some kind of id, let's say 'abc123' for the sake of this example
app.use(store); //not relevant for this answer
app.mount(section);
然后,在组件内部,通过执行以下操作可以访问“数据集”。
MyComponent.vue
<template>
<div>Normal template stuff here</div>
</template>
<script>
export default {
name: 'MyComponent',
inject: ['dataset'], // the magic
created() {
console.log(this.dataset); // will log 'abc123'
}
}
</script>
这很简单,但是我想很好地展示了我的情况。无论如何,如果您尝试做类似的事情并且想通过父数据属性获取数据,则可以考虑提供/注入。
希望它可以帮助任何人!
答案 1 :(得分:0)
您可以使用getCurrentInstance
。 Vue documentation。
这很容易:
import { getCurrentInstance } from "vue";
export default {
setup(props) {
const instance = getCurrentInstance();
console.log("parent");
console.log(instance.parent);
}
}
另外,可能值得注意的是,Vue composition api plugin以相同的方式公开了父对象,但是在此它被称为instance.$parent
。