【发布时间】:2021-11-22 01:13:05
【问题描述】:
我有一个简单的 div 和一个 v-for 循环,可以在页面上显示项目。这些项目上有一个class,我想使用 Javascript 的querySelector 方法来选择。
<div class="product-feed">
<div v-for="Product in ProductFeed" :key="Product.ProductID" class="product-item" >
<Product-Vue-Component :Product="Product"></Product-Vue-Component>
</div>
</div>
<script>
...
setup(){
async function loadFeed(){
await nextTick();
let element1 = document.querySelector('.product-feed');
console.log(`element1`, element1) // this works and displays the element
let element2 = document.querySelector('.product-item:last-of-type');
console.log(`element2`, element2) // this comes back as null
}
}
onMounted(()=> {
loadFeed();
})
}
...
</script>
即使我正在等待 DOM 使用 nextTick() 渲染,函数 loadFeed() 也无法获取 v-for 循环中的任何项目。
我需要检测v-for 循环中的项目,以便我可以实现无限滚动功能,当用户滚动到.product-item 元素列表的底部时会加载更多项目(因此:last-of-type 伪选择器)
哪里出了问题,可以这样选择元素吗?
【问题讨论】:
-
在孤立示例中一切正常:jsfiddle.net/matvey_andreyev/4qgny59j/2 您确定您的 ProductFeed 在 onMounted + nextTick 时间可用吗?
-
@MatveyAndreyev 谢谢你的测试,那一定是种族问题
标签: javascript vue.js vuejs3