vue3的createApp返回一个应用实例,实例上提供了directive方法,生成自定义指令,定义这个指令后使用v-指令名的方式绑定元素即可。
const app = createApp(App)
app.directive("scrollBottom", {
updated(el) {
// 这里的el即是绑定指令处的dom元素
el.scrollTo({
top: el.scrollHeight - el.clientHeight,
behavior: "smooth"
})
}
})
绑定使用的元素
<div class="scroll" v-scrollBottom>
<div class="scroll-item" v-for="item in num">{{ item }}</div>
</div>
完整vue页面示例
<template>
<section class="home">
<button @click="add">增加</button>
<div class="scroll" v-scrollBottom>
<div class="scroll-item" v-for="item in num">{{ item }}</div>
</div>
</section>
</template>
<script lang="ts" setup>
import { ref } from "vue"
const num = ref(5)
function add() {
num.value++
}
</script>
<style lang="less">
.home {
.scroll {
height: 600px;
overflow: auto;
.scroll-item {
width: 300px;
height: 200px;
margin-bottom: 20px;
background-color: skyblue;
}
}
}
</style>