Vue 3中如何实现滚动到指定元素的变量?
P粉060528326
P粉060528326 2023-08-28 20:17:07
[Vue.js讨论组]
<p>我在纯JavaScript中有以下函数来滚动到一个元素,我想将这段代码转换为Vue 3。</p> <pre class="brush:php;toolbar:false;">var source = '' function showScrollInto(currentLocation, toLocation) { source = currentLocation // 在隐藏部分后返回的位置 document.getElementById(toLocation).style.display = 'block' document.getElementById(toLocation).scrollIntoView() }</pre> <p>并返回到原始位置:</p> <pre class="brush:php;toolbar:false;">document.getElementById(source).scrollIntoView()</pre> <p>在点击按钮时调用showScrollInto:</p> <pre class="brush:php;toolbar:false;">&lt;button onClick=&quot;showScrollInto('top', 'interesse')&quot;&gt;TITLE&lt;/button&gt;</pre> <p>现在我将该函数转换为一个方法并尝试:</p> <pre class="brush:php;toolbar:false;">import { ref } from &quot;vue&quot; var source = &quot;&quot; const toLocation = ref('Vue.js') export default { name: &quot;App&quot;, 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() } } }</pre> <p>通过点击按钮调用showScrollInto:</p> <pre class="brush:php;toolbar:false;">&lt;button @click=&quot;showScrollInto($event, 'kosten', 'interesse')&quot;&gt;TITLE&lt;/button&gt;</pre> <p>要滚动到的元素如下:</p> <pre class="brush:php;toolbar:false;">&lt;section class = &quot;top-level-section&quot; v-show=&quot;!hideInteresse&quot; ref=&quot;interesse&quot;&gt;</pre> <p>传递变量到方法中是可以的,但我无法弄清楚如何滚动到一个位置,其中位置是一个变量。</p> <p>this.$refs.interesse.scrollIntoView({ behavior: 'smooth'}) 可以用于滚动到id为'interesse'的元素,但我不知道如何将该元素名称转换为一个变量。 此外,我了解到this.$refs不是Vue 3的表示法,应该转换为类似ref('value')的形式,但我不知道如何做到这一点。</p>
P粉060528326
P粉060528326

全部回复(1)
P粉282627613

首先,阅读Vue的文档关于模板引用的部分。页面左上角有一个切换按钮,可以在选项API和组合API语法之间切换。

使用变量引用引用取决于您使用的Vue版本和/或语法。

<div ref="someRefName"></div>

Vue 2 / 选项API

变量应该是与元素上的ref匹配的字符串

const refVar = "someRefName"
this.$refs[refVar].scrollIntoView({ behavior: "smooth" });

Vue 3 / 组合API

变量应该被赋值为ref()(需要导入)。常量的名称应该与元素上的ref名称匹配

const someElement = ref() // 赋值给模板中的某个元素
someElement.value.scrollIntoView({ behavior: "smooth" });

选项API和组合API不应混合使用,所以只使用一种语法。

在这两种情况下,您可以有多个具有相同ref名称的元素,此时Vue将创建一个包含所有相同名称ref的数组,因此要访问特定的元素,您还需要使用索引。

以下是一些简化的示例。希望它们能解决您的剩余问题,并且您可以根据需要进行修改。

选项API codesandbox示例

组合API codesandbox示例

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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