首页 > 解决方案 > 如何在函数参数中定义/使用“el”(vue js)

问题描述

我是 VueJS 初学者,所以请多多包涵。

使用“?”时,我需要编写代码以滚动到 id 元素 在网址中。效果和这个一样

但我已经用修复格式关注了这个问题,因为这是我的任务。他们在没有document.getElementById(Query.query).scrollIntoView({behavior: "smooth" });. 我已经通过添加上面的代码完成了结果。但我不知道如何分成 2 个功能。而且我也不知道如何使用“el”参数调用scrollToHere()。

scrollToHere() 没有在其他地方调用,所以我必须在 anchor() 中包含这个函数,但我不知道怎么做。这个“el”是干什么用的?如何分离代码?任何指导将不胜感激。

<div id="scroll_here"></div>
methods: {
    anchor() {
        console.log(Query)  //query: "scroll_here"            
        document.getElementById(Query.query).scrollIntoView({behavior: "smooth" });  
    },
    scrollToHere (el) {
         // CODE HERE
    },
}

标签: javascriptvue.jsvuejs3js-scrollintoview

解决方案


原始答案el中的项目是指您打算滚动到的项目。HTMLElement

这是一个两两的过程。首先找到元素,然后向它滚动。

// Assuming this is the html - <div id="scroll_here"></div>

// 1. Find the element using one of the two ways
const el = document.getElementById('scroll_here');

// or alternately,
const el = document.querySelector('#scroll_here');


// 2. Scroll that element into view.
el.scrollIntoView();

您可以使用getElementByIdquerySelector来获取 DOM 树中 HTML 元素的引用。

在您的情况下,您可以在方法中获取元素引用anchor()并将其传递给scrollToHere()函数,例如:

methods: {
  anchor() {
    // { query: "scroll_here" }
    console.log(Query);
    
    this.scrollToHere(document.getElementById(Query.query));
  },
  scrollToHere(el) {
    el.scrollIntoView({behavior: "smooth" });
  }
}

推荐阅读