gpt4 book ai didi

vue.js - 有没有办法访问 Vue $scopedSlots 挂载的 DOM 元素?

转载 作者:行者123 更新时间:2023-12-04 09:48:00 25 4
gpt4 key购买 nike

我有一个名为 myElement 的作用域插槽,我可以通过 this.$scopedSlots.myElement()[0] 访问它。

通常当挂载一个 vnode 时,会有一个包含 DOM 元素的 $el,但显然不在作用域插槽中,只有一个未定义的 elm

我还尝试在子模板中的插槽上放置一个 ref,并通过 .context.$refs 访问它,但它仅列出父模板上的 refs。

如果子组件不知道它的 id 或 class,我有什么方法可以访问已挂载的 DOM 元素?

谢谢


更多详情:

父模板(Pug)

child-component
template(v-slot:myelement="{ on }")
span My element content

子组件

  mounted () {
console.log(this.$scopedSlots.myelement()[0])
// From here I want to get the position of the span with
// span.getBoundingClientRect()
}

转载链接:

https://codepen.io/antoniandre/pen/BaogjrM?editable=true&editors=101

最佳答案

所以像这样的东西可以用来解决问题:

mounted () {
const myEl = this.$scopedSlots.myelement()[0];
if(myEl.data && myEl.data.attrs && myEl.data.attrs.id){
const id = myEl.data.attrs.id
console.log([this.$el.querySelector('#id')])
} else {
throw new Error('slot myelement needs an id');
}
}

或者强行应用一个id:

const Child = {

render: function(h){
const myEl = this.$scopedSlots.myelement()[0]
myEl.data = {attrs: {id: 'id'}};
console.log(myEl)
return h('div', {}, [myEl])
},

mounted () {
console.log([this.$el.querySelector('#id')])
}
}

关于vue.js - 有没有办法访问 Vue $scopedSlots 挂载的 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com