首页 > 解决方案 > 为什么不将 scrollIntoView 应用于 vuejs 中的选定元素?

问题描述

我目前正试图让它滚动到视图的一部分,如下所示:

mounted: function() {
    const el = this.$el.getElementsByClassName('outstandingStandarItems')[0];
    if(el){
        el.scrollIntoView({behavior: 'smooth'});
        console.log(el);
    }
  }

在控制台上打印如下: 在此处输入图像描述

但这并不适用:el.scrollIntoView({behavior: 'smooth'});

我应该去的部分是这样的:

<el-card shadow="never" class="box-card outstandingStandarItems" v-if="isOutstanding">
</el-card>

我需要scrollIntoView在加载视图时应用它,这就是我将它安装在其中的原因。如果我将它添加到一个方法中,然后添加一个按钮以转到该方法,那么它确实会正确应用它。

<el-button @click="gotoOutStanding()">GOT OUT</el-button>

gotoOutStanding(){
  this.$refs.outstandingItems.$el.scrollIntoView({behavior: 'smooth'});
},

但是我需要在视图加载时自动发生这种情况。

标签: javascriptvuejs2

解决方案


我认为问题出在:

const el = this.$el.getElementsByClassName('outstandingStandarItems')[0];

你应该尝试使用 $refs:

<el-card shadow="never" ref="items" class="box-card outstandingStandarItems" v-if="isOutstanding">
</el-card>

接着:

const el = this.$ref.item;

为了更深入的了解去这里


推荐阅读