我遇到了Vue 3 (alpha 4)的问题:
在setup()
函数中,我正在尝试读取父组件。根据https://vue-composition-api-rfc.netlify.com/api.html#setup上的文档,它应该通过context
参数公开父级,要么作为context.attrs的属性,要么直接作为父级(参见“键入”下面的SetupContext
位)。对于应该直接从SetupContext
访问parent
,还是通过SetupContext.attrs
访问,我发现文档并不是很清楚,所以我尝试了两种方法,但都没有用。
这是我的问题,我可以访问SetupContext
和SetupContext.attrs
(这是一个代理),在记录它们的时候就可以了。SetupContext.attrs
公开了通常的代理属性([[Handler]]
、[[Target]]
和[[IsRevoked]]
),当检查[[Target]]
时,它会清楚地显示父property。
但是,当记录父级时,它只是打印出未定义的:
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
}
};
传播上下文会产生相同的结果:
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
}
};
我对JavaScript中的代理还是个新手,但从我在代理上读到的内容,以及对reactive()返回的代理的体验来看,我是个新手。我应该能够像通常使用对象一样访问该属性。知道我哪里做错了吗?
我已经创建了一个codesandbox来重现这个问题
发布于 2020-12-15 11:09:05
您可以使用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以同样的方式公开了parent,但它在那里被引用为instance.$parent
。
发布于 2020-12-04 00:09:48
我知道这不能直接回答这个问题,但是使用provide/inject (https://v3.vuejs.org/guide/component-provide-inject.html)已经帮助我解决了这个问题,我想从父节点获取数据属性并将其传递给呈现的组件,但在从Vue2升级到Vue3后无法再访问父节点。我没有尝试公开父组件,而是从它的数据集向下传递了一个属性到呈现的组件。
在创建应用程序时,我执行了以下操作。
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>
这是非常精简的,但我想很好地展示了我的情况。在任何情况下,如果您正在尝试执行类似的操作,并且希望通过父数据属性获取数据,则可以查看provide/inject。
希望这对任何人都有帮助!
https://stackoverflow.com/questions/60270794
复制相似问题