問題描述:
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.documentElemen
t對象,它上面有滾動條就會觸發返回頂部。
解決方案二:傳入正確的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
,這樣纔可以。