增删改案例(Vue)

46 阅读1分钟

image.png

步骤:

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;
      }
    },
  },
};