增删改案例(Vue)

本文介绍了如何在Vue.js应用中使用数组操作(push、splice和watch)来管理动态列表,包括添加新语言、编辑元素值以及删除元素的实现过程。
摘要由CSDN通过智能技术生成

在这里插入图片描述

步骤:

1.添加操作:当有新语言时给数组push添加元素
2.编辑操作:更换元素
3.删除操作:splice方法
4.watch侦听器替换元素

html

 <div id="app">
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
        <button @click="editItem(index)">编辑</button>
        <button @click="deleteItem(index)">删除</button>
      </li>
    </ul>
    <input v-model="newItem" placeholder="添加语言">
    <button @click="addItem">添加</button>
  </div>

js

export default {
  data() {
    return {
      items: ['css', 'js', 'html'],
      newItem: '',
      curItem: null,
    };
  },
  methods: {
   // 添加操作
    addItem() {
			// console.log(this.newItem.trim());
			// 当写出新的语言时 trim 移除字符串两侧的空格字符或其他预定义字符
      if (this.newItem.trim()) {
				// 在数组后面添加新的元素
        this.items.push(this.newItem.trim());
				// 清空input输入框
        this.newItem = '';
      }
    },
		// 编辑操作
    editItem(index) {
			// console.log(index);
			// 将index值赋值给curItem
      this.curItem = index;
			// console.log(this.items[index]);
			// 编辑的元素里的值
      this.newItem = this.items[index];
    },
    deleteItem(index) {
      this.items.splice(index, 1);
    },
  },
  watch: {
    newItem(val) {
			// console.log(this.curItem);
			// 目前数组元素的索引号
      if (this.curItem !== null) {
				// 替换元素
        this.items.splice(this.curItem, 1, val.trim());
        this.curItem = null;
      }
    },
  },
};
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值