this.$refs.item1.scrollIntoView is not a function,this.$refs[index].scrollIntoView is not a function

在Vue开发中遇到使用ref进行屏幕滚动时的错误,问题在于v-for循环中ref获取到的是一个数组。解决方案是通过索引访问数组元素,如`this.$refs['item' + _index][0].scrollIntoView()`。此外,还可以统一ref名称并通过index参数操作对应DOM。
摘要由CSDN通过智能技术生成

今天使用Vue过程中,使用ref去操作dom想要实现屏幕滚动效果时报错,his.$refs[index].scrollIntoView is not a function和this.$refs.item1.scrollIntoView is not a function;

报错截图和代码如下:

<div v-for="(item,index) in [{name:'test1'},{name:'test2'}]" @click="clickItem(index)">
  <div :ref="'item'+index" style="height: 500px;background-color: white;margin-top: 10px">
    {{ item.name }}
  </div>
</div>
clickItem: function (_index) {
  this.$refs[`item${_index}`].scrollIntoView(
      {
        behavior: "smooth",  // 平滑过渡
        block: "start"  // 上边框与视窗顶部平齐。默认值
      }
  );
},

 一开始以为是我方法中模板字符串用的有问题,于是尝试指定特定ref:改为this.$refs.item1和this.$refs['item1'],

clickItem: function (_index) {
  this.$refs.item1.scrollIntoView(
      {
        behavior: "smooth",  // 平滑过渡
        block: "start"  // 上边框与视窗顶部平齐。默认值
      }
  );
},

结果还是报错

然后通过调试 发现获取的ref是一个数组

  

然后划重点!!通过搜索了一番,发现ref加在普通元素上,this.$refs.name获取的是dom元素,用在v-for时,获取的是包含一组dom的数组。

最直接的解决办法是将下标设为0,通过this.refs.[`item${_index}`][0]获取指定的dom结构;

clickItem: function (_index) {
  this.$refs[`item${_index}`][0].scrollIntoView(
      {
        behavior: "smooth",  // 平滑过渡
        block: "start"  // 上边框与视窗顶部平齐。默认值
      }
  );
},

成功解决!!!

上述方法是将dom元素上的ref指向了变量item0、item1等,同理由数组可知ref不同于id,不是唯一标识的,可以在v-for中将ref命名为统一名称,通过v-for中的index索引传递给js函数的参数中进行相应dom的操作,如下图 为另一种写法:

<div ref="item" v-for="(item,index) in [{name:'test1'},{name:'test2'}]" @click="clickItem(index)">
  <div style="height: 500px;background-color: white;margin-top: 10px">
    {{ item.name }}
  </div>
</div>
clickItem:function (_index){
  this.$refs.item[_index].scrollIntoView(
      {
        behavior: "smooth",  // 平滑过渡
        block: "start"  // 上边框与视窗顶部平齐。默认值
      }
  );

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值