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

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

<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>
template>
<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>

你可能感兴趣的:(vue.js,javascript,前端,es6)