【问题标题】:Why does querySelector not work with v-for?为什么 querySelector 不能与 v-for 一起使用?
【发布时间】: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


【解决方案1】:

尝试使用class="product-item"在div上设置ref

<div ref="el" v-for="Product in ProductFeed" :key="Product.ProductID" class="product-item" >

然后在设置函数中:

const el = ref(null)

onMounted(() => {
    loadFeed()
  })

async function loadFeed(){
  await nextTick();
    let element1 = document.querySelector('.product-feed'); 
    console.log(`element1`, element1) // this works and displays the element

    console.log(el.value) 
  }
}
return {el}

【讨论】:

  • 你如何获得最后一个.product-item
  • 嘿伙计,我测试过,el.value 得到最后一个元素
【解决方案2】:

请使用 refs,只需将 ref 属性添加到容器 ref="productFeed" 并获取此元素

import { ref } from 'vue'
...    
const productFeed = ref(null)
...
return {
    productFeed
}

那么就可以使用productFeed.value作为变量,包含dom元素

【讨论】:

  • 而for循环使用this
  • 我需要product-item 而不是ProductFeed
  • 为此,我为您留下了一个链接,在您的 product-item 元素上写 :ref="el =&gt; { if (el) divs[i] = el }" 为您的元素 const divs = ref([]) 创建一个变量,在更新时清除它 onBeforeUpdate(() =&gt; { divs.value = [] }),并使用 @987654330 @ 作为 domElements 数组
【解决方案3】:

尝试像这样使用refs

<div
  v-for="Product in ProductFeed" :ref="`product--${Product.id}`">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 2021-06-14
    • 2012-10-09
    • 2020-03-18
    • 2017-11-21
    • 2019-04-11
    • 2012-09-19
    • 2013-12-30
    相关资源
    最近更新 更多