You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中watch内scrollIntoView滚动失效问题求助

输入框匹配值时自动滚动失效的解决办法

问题场景

输入框通过v-model绑定searchAddress,当输入值等于"1"时,期望页面自动滚动到.here元素,但该功能失效;点击按钮调用同一scrollToView函数却能正常触发滚动。

问题根源

输入框在输入内容后,浏览器会自动滚动到输入框所在位置以保证焦点可见,这个默认行为会覆盖手动调用scrollIntoView的滚动效果。即使使用nextTick,也无法避开浏览器的这个默认滚动时机,两者执行顺序导致自定义滚动被覆盖。

解决方案

通过setTimeout延迟执行滚动逻辑,给浏览器的默认焦点滚动留出完成时间,确保自定义滚动操作在之后执行:

修改监听matchAddress的代码:

watch(matchAddress, (val) => {
  console.log(val);
  if (val) {
    // 延迟100ms执行,避开浏览器输入框焦点滚动的时机
    setTimeout(() => {
      scrollToView();
    }, 100);
  }
});

完整修改后代码

<template>
  <button @click="scrollToView">Click to Here</button>
  <input type="text" v-model="searchAddress" />
  <span v-if="matchAddress">OK</span>
  <span class="here" ref="el">Here</span>
</template>

<script setup>
import { ref, computed, watch } from "vue";
const searchAddress = ref(null);
const el = ref(null);
const matchAddress = computed(() => {
  return searchAddress.value == 1;
});
function scrollToView() {
  el.value.scrollIntoView({ behavior: "smooth", block: "center" });
  el.value.focus({ preventScroll: true });
}
watch(matchAddress, (val) => {
  console.log(val);
  if (val) {
    setTimeout(() => {
      scrollToView();
    }, 100);
  }
});
</script>

内容的提问来源于stack exchange,提问作者Criss Anger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:20:49