使用scrollIntoView()的VueJS组件

ben*_*mon 6 html javascript getelementbyid vue.js vue-component

我正在尝试在vue组件中使用document.getElementById().scrollIntoView()来使用Jump-To-Div类型的功能.

如果我在组件中调用该函数,该功能可以正常工作.但是如果我尝试使用ref从父组件调用该函数,则该元素不会滚动到视图中.

父组件是页面,子组件是页面中的选项卡.

这是父组件中的子Vue组件: -

<el-tab-pane label="Solution Details" name="Solution Details" v-loading="loading">
                <solution-details
                    :formData="response"
                    ref="solutionDetails"
                    @done="$emit('done')">
                </solution-details>
            </el-tab-pane>
Run Code Online (Sandbox Code Playgroud)

所以有一个SolutionDetails.Vue子组件,它有一个ref ="solutionDetails".我使用子组件的ref 在父组件中调用此方法:

handleClick(command) {
            this.activeTab = 'Solution Details';
            this.$refs.solutionDetails.showCurrent(command);
        },
Run Code Online (Sandbox Code Playgroud)

子组件中有一个showCurrent函数,它应该为参数"command"执行.这是子组件中的该函数.

methods: {
        showCurrent(index) {
            document.getElementById(index).scrollIntoView();
        },
Run Code Online (Sandbox Code Playgroud)

如您所见,showCurrent应该获取页面中的元素并应滚动到视图中.如果SolutionDetails.vue是活动选项卡,则相应的元素将完全滚动到视图中.但我正在从其他选项卡执行父函数,然后this.activeTab = 'Solution Details';正在执行,即.活动选项卡正在更改为SolutionDetails.vue,但请求的元素不会滚动到视图中.

当其他标签是activeTab时,我该怎么做才能滚动到一个元素?

Ber*_*ert 9

问题是在页面上呈现选项卡之前scrollIntoView调用,因为呈现是异步的.基本上,当你打电话

this.activeTab = 'Solution Details';
Run Code Online (Sandbox Code Playgroud)

Vue不会立即呈现页面,它只是对渲染进行排队.然而,在此之后,您立即告诉Vue寻找渲染的元素并滚动到它.它还没有.

我想我第一次尝试解决这个问题就是使用$ nextTick.

this.$nextTick(() => this.$refs.solutionDetails.showCurrent(command))
Run Code Online (Sandbox Code Playgroud)

这应该等待在您尝试滚动到视图之前需要发生的渲染.


小智 7

实际上,您必须引用组件中的元素。例如这样的事情:

this.$refs.[ref name here].$el.scrollIntoView({ behavior: 'smooth' });
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果将 ref 添加到常规 HTML 元素(而不是自定义 Vue 元素),则不应使用 `$el`。有关更多详细信息,请参阅此答案:/sf/answers/4087516961/ (6认同)