我试图滚动到一个特定的元素点击。但我得到了以下错误。
Uncaught TypeError: element.scrollIntoView is not a function这是我的剧本
<script setup>
import { ref } from 'vue'
function goTo(refName){
let element = ref(refName);
element.scrollIntoView({behavior: "smooth"})
}
</script>这是我的点击功能
<DayWithText v-for="day in daysOfWeek" :name="day.shortHand" :day="day.day" :date="day.date" @click.prevent="goTo('test')"/>这就是元素
<p ref="test">test</p>我做错了什么?
发布于 2022-07-09 11:44:38
ref('test')不返回<p ref="test">test</p>。它创建一个新的ref,初始值为'test' (string)。
要得到这一段,你必须声明为
const test = ref(null)内部<script setup> (在mount之前)。
在组件安装后的任何时候
test.value?.scrollIntoView({behavior: "smooth"})会起作用的。
演示:
const { createApp, ref } = Vue;
createApp({
setup() {
const test = ref(null);
const goToTest = () => {
test.value?.scrollIntoView({behavior: "smooth", block: "center"})
}
return {
test,
goToTest
}
}
}).mount('#app')#app p {
margin: 200vh 0;
}<script src="https://unpkg.com/vue@3.2/dist/vue.global.prod.js"></script>
<div id="app">
<button @click="goToTest">Go to test</button>
<p ref="test">test</p>
</div>
在mount的遮罩下,当<template>解析器找到一个ref时,它将查找具有该名称的声明变量的setup范围。如果找到并且如果它是一个ref,那么当前的DOM元素将放置在该引用的value中。
https://stackoverflow.com/questions/72920333
复制相似问题