Vue 3中如何实现滚动到指定元素的变量?
P粉060528326
P粉060528326 2023-08-28 20:17:07
[Vue.js讨论组]

我在纯JavaScript中有以下函数来滚动到一个元素,我想将这段代码转换为Vue 3。

var source = ''
function showScrollInto(currentLocation, toLocation) {
  source = currentLocation  // 在隐藏部分后返回的位置
  document.getElementById(toLocation).style.display = 'block'
  document.getElementById(toLocation).scrollIntoView()
}

并返回到原始位置:

document.getElementById(source).scrollIntoView()

在点击按钮时调用showScrollInto:

<button onClick="showScrollInto('top', 'interesse')">TITLE</button>

现在我将该函数转换为一个方法并尝试:

import { ref } from "vue"
var source = ""
const toLocation = ref('Vue.js')

export default {
    name: "App",
    data() {
        return {
            hideAlleClubs: true,
            hideIkWilKennismaken: true,
            hideAlleLocaties: true,
            hideMeerOverKegelen: true,
            hideInteresse: true
        }
    },
    methods: {
        showScrollInto(event, currentLocation, toLocation) {
            source = currentLocation  // 在隐藏部分后返回的位置
            this.hideInteresse = false
            this.$refs.toLocation.scrollIntoView({ behavior: 'smooth'})
            // document.getElementById(toLocation).style.display = 'block'
            // document.getElementById(toLocation).scrollIntoView()
        }
    }
}

通过点击按钮调用showScrollInto:

<button @click="showScrollInto($event, 'kosten', 'interesse')">TITLE</button>

要滚动到的元素如下:

<section class = "top-level-section" v-show="!hideInteresse" ref="interesse">

传递变量到方法中是可以的,但我无法弄清楚如何滚动到一个位置,其中位置是一个变量。

this.$refs.interesse.scrollIntoView({ behavior: 'smooth'}) 可以用于滚动到id为'interesse'的元素,但我不知道如何将该元素名称转换为一个变量。 此外,我了解到this.$refs不是Vue 3的表示法,应该转换为类似ref('value')的形式,但我不知道如何做到这一点。

P粉060528326
P粉060528326

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号