当前位置:首页 > VUE

vue 实现添加删除 div

2026-02-23 04:01:42VUE

添加和删除 div 的基本实现

在 Vue 中,可以通过 v-for 和数组操作实现动态添加和删除 div 元素。以下是一个基础示例:

<template>
  <div>
    <button @click="addDiv">添加 Div</button>
    <div v-for="(item, index) in divList" :key="index">
      {{ item.content }}
      <button @click="removeDiv(index)">删除</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      divList: []
    }
  },
  methods: {
    addDiv() {
      this.divList.push({
        content: `Div ${this.divList.length + 1}`
      })
    },
    removeDiv(index) {
      this.divList.splice(index, 1)
    }
  }
}
</script>

使用唯一标识符

为每个 div 分配唯一 ID 可以避免渲染问题:

vue 实现添加删除 div

data() {
  return {
    divList: [],
    nextId: 1
  }
},
methods: {
  addDiv() {
    this.divList.push({
      id: this.nextId++,
      content: `Div ${this.nextId}`
    })
  }
}

动画效果

可以为添加/删除操作添加过渡动画:

vue 实现添加删除 div

<template>
  <div>
    <transition-group name="fade" tag="div">
      <div v-for="item in divList" :key="item.id">
        {{ item.content }}
        <button @click="removeDiv(item.id)">删除</button>
      </div>
    </transition-group>
  </div>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

复杂内容结构

每个 div 可以包含更复杂的结构和数据:

addDiv() {
  this.divList.push({
    id: this.nextId++,
    title: `标题 ${this.nextId}`,
    content: '这里是内容',
    timestamp: new Date().toLocaleString()
  })
}

删除确认

添加删除确认对话框:

removeDiv(id) {
  if(confirm('确定要删除吗?')) {
    this.divList = this.divList.filter(item => item.id !== id)
  }
}

这些方法提供了从基础到进阶的 Vue 实现方案,可根据实际需求选择合适的实现方式。

标签: vuediv
分享给朋友:

相关文章

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些方…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue滚动实现

vue滚动实现

Vue 滚动实现方法 使用原生滚动 在 Vue 中可以通过 ref 获取 DOM 元素,调用原生滚动方法实现滚动效果。适用于简单场景。 <template> <div ref=…

vue实现type切换

vue实现type切换

Vue 实现 Type 切换的实现方法 在 Vue 中实现 Type 切换功能可以通过动态组件、条件渲染或路由切换等方式实现。以下是几种常见方法: 使用 v-if 或 v-show 条件渲染 通过绑…

vue实现div单选

vue实现div单选

Vue 实现 div 单选 在 Vue 中实现 div 单选可以通过 v-model 结合 v-for 和事件绑定来完成。以下是具体实现方法: 模板部分 <template>…