Home > OS >  Vue3 - scrollIntoView in watch
Vue3 - scrollIntoView in watch

Time:01-25

I want to type in the input, and if the value of input matches "1" it will scroll to .here, but it isn't working,

I tried creating a button and adding a handle-click function. It worked.

Please help me.

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

<script setup>
import { ref, computed, watch, nextTick } 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, async (val) => {
  console.log(val);
  if (val) {
    await nextTick();
    scrollToView();
  }
});
</script>

DEMO

CodePudding user response:

You could try something like this. This is vanilla JS though. In Vue you just need to change the onkeyup(event) to @keyup($event). And the window.scrollTo might need to change to outerComponent.scrollTo. Just type "1" into the input.

function checkValue(event) {
  const inputVal = event.currentTarget.value
  const hereDiv = document.querySelector('.here')
  if (inputVal === '1') {
    
    // In Vue you might have to change "window" to the to your outer component ref.
    window.scrollTo({ 
      top: hereDiv.offsetTop,
      behavior: 'smooth'
    })
  }
}
.here {
  width: 50px;
  height: 50px;
  margin-top: 800px;
  background-color: blue;
}
<input type="text" onkeyup="checkValue(event)">
<div >

CodePudding user response:

So, seems to be an issue with Chrome. Apparently, the nextTick() hits too early. I think there is an even from keyup which stops Chrome from scrolling the <input> out of view. That is why the button works, but not the text input.

It works if you put it into a setTimeout():

watch(matchAddress, async (val) => {
  if (val) {
    setTimeout(() => scrollToView());
  }
});
  • Related