当前位置:首页 > VUE

vue实现添加删除

2026-01-15 02:19:10VUE

Vue 实现添加和删除功能

在 Vue 中实现添加和删除功能通常涉及数据绑定、事件处理和列表渲染。以下是实现方法:

数据绑定与列表渲染

使用 v-for 指令渲染列表,并通过 v-model 绑定输入数据:

vue实现添加删除

<template>
  <div>
    <input v-model="newItem" placeholder="输入新项">
    <button @click="addItem">添加</button>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
        <button @click="removeItem(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

添加功能实现

在 Vue 实例的 methods 中定义 addItem 方法,将新项添加到数组:

<script>
export default {
  data() {
    return {
      newItem: '',
      items: []
    }
  },
  methods: {
    addItem() {
      if (this.newItem.trim()) {
        this.items.push(this.newItem)
        this.newItem = ''
      }
    }
  }
}
</script>

删除功能实现

通过数组的 splice 方法移除指定索引的项:

vue实现添加删除

methods: {
  removeItem(index) {
    this.items.splice(index, 1)
  }
}

使用计算属性优化

对于需要派生状态的情况(如空值检查),可以使用计算属性:

computed: {
  isInputEmpty() {
    return this.newItem.trim() === ''
  }
}

添加动画效果

通过 Vue 的 <transition-group> 为列表添加动画:

<transition-group name="list" tag="ul">
  <li v-for="(item, index) in items" :key="index">
    {{ item }}
    <button @click="removeItem(index)">删除</button>
  </li>
</transition-group>

完整组件示例

<template>
  <div>
    <input 
      v-model="newItem" 
      placeholder="输入新项"
      @keyup.enter="addItem"
    >
    <button 
      @click="addItem" 
      :disabled="isInputEmpty"
    >
      添加
    </button>

    <transition-group name="fade" tag="ul">
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
        <button @click="removeItem(index)">删除</button>
      </li>
    </transition-group>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newItem: '',
      items: []
    }
  },
  computed: {
    isInputEmpty() {
      return this.newItem.trim() === ''
    }
  },
  methods: {
    addItem() {
      if (!this.isInputEmpty) {
        this.items.push(this.newItem.trim())
        this.newItem = ''
      }
    },
    removeItem(index) {
      this.items.splice(index, 1)
    }
  }
}
</script>

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

标签: vue
分享给朋友:

相关文章

课程表vue实现

课程表vue实现

实现课程表的Vue组件 创建课程表需要设计数据结构、布局和交互逻辑。以下是一个基于Vue 3的实现方案: 数据结构设计 const timetableData = ref([ { ti…

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

vue实现pie

vue实现pie

Vue 实现饼图 在 Vue 中实现饼图通常可以通过第三方图表库(如 ECharts、Chart.js 或 Highcharts)来完成。以下是使用 ECharts 和 Chart.js 的两种常见方…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…

vue实现全屏

vue实现全屏

Vue 实现全屏功能的方法 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 来实现。以下是几种常见的实现方式: 使用原生 Fullscreen API 通过调用 doc…

vue实现切换

vue实现切换

Vue 实现切换功能的方法 在 Vue 中实现切换功能可以通过多种方式实现,以下是一些常见的方法: 使用 v-if 和 v-else 指令 通过条件渲染实现切换功能,适用于简单的显示/隐藏场景。…