vue中将新添加的div标签自动定位到可视区域内

可以结合使用Vue的ref和scrollIntoView()方法来实现

html 复制代码
<template>
  <div>
    <button @click="addDiv">添加新的<div>标签</button>
    <div ref="container" class="container">
      <div v-for="(item,index) in divs" :key="index" ref="divElement" class="div-element">
        <!-- 此处为动态添加的div内容 -->
      </div>
    </div>
  </div>
</template>
javascript 复制代码
<script>
export default {
  data() {
    return {
      divs: []
    };
  },
  methods: {
    addDiv() {
      this.divs.push({name:'小明'})
      this.$nextTick(() => {
        const divElement = this.$refs.divElement[this.$refs.divElement.length - 1]; 
        //this.$refs.divElement.length - 1   取的是该数组中的最后一个
        if (divElement) {
          divElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
        }
      });
    }
  }
};
</script>
相关推荐
passerby60612 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了2 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅2 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅3 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅3 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅3 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼4 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
吹牛不交税4 小时前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore