Element-ui 遇到的坑之返回顶部Backtop组件的target如何设置正确的值的问题。

问题描述:

element-ui 的Backtop属性中有target的值是需要设置的。设置错了,不仅没有效果,反而还可以导致报错。

官方文档说明的是,target触发滚动的对象,String类型。

查看示例,是传一个css选择符。

查看官方源码,我们会发现,

  init() {
      this.container = document;
      this.el = document.documentElement;
      if (this.target) {
        this.el = document.querySelector(this.target);
        if (!this.el) {
          throw new Error(`target is not existed: ${this.target}`);
        }
        this.container = this.el;
      }
    },

target是有默认值的,默认值是document.documentElement对象。我们传入一个css选择器进去后,就会替换为document.querySelector(this.target)选择的dom节点。

废话不多说,重点说一下解决方法。

解决方案一:什么都不传,用默认值。

<template>
  <div class="appmain-wrap">
    <!-- 返回顶部 -->
    <el-backtop></el-backtop>
     <!-- 其他代码-->
</template>

这个时候,backtop拿到的是document.documentElement对象,它上面有滚动条就会触发返回顶部。

解决方案二:传入正确的target的值。

譬如我是在一个tabs页面使用的示例。

<template>
  <div class="appmain-wrap">
	<el-tabs v-model="activeName" @tab-click="handleClick">
	  <el-tab-pane label="用户管理" name="first">用户管理
	  	<el-backtop target=".appmain-wrap"></el-backtop>
	  	<!-- 其他代码-->
	  </el-tab-pane>
    <el-tab-pane label="配置管理" name="second">配置管理</el-tab-pane>
  </el-tabs>
  </div>
</template>

这个时候,还是不行,需要给.appmain-wrap加一个样式

.appmain-wrap {
  height: 100vh;
  overflow: scroll;
}

给这个target的壳,设置height高度,然后设置overflow:scroll,这样才可以。

猜你喜欢

转载自blog.csdn.net/qq_42991509/article/details/106059298