欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue的增删改查.

程序员文章站 2022-07-04 19:24:23
...

废话不多说!增删改查,总的来说还是数组方法 .

  • push、indexOf、filter、pop、splice…
<template>
  <!-- 增删改查 -->
  <div class="person">
    <div>id:<input v-model="id" :disabled="disabled" /></div>
    <div>name:<input v-model="name" /></div>
    <!-- 新增 -->
    <button @click="newPerson">{{ commonBtnInfo }}</button>
    <!-- 修改 -->
    <button v-show="showChangeInfo" @click="xiugai">
      {{ commonBtnInfos }}
    </button>
    <!-- 内容 -->
    <div>增删改查的内容</div>
    <ul v-for="(item, index) in filterPerson" :key="index">
      <li>
        {{ item.id }} <span>{{ item.name }}</span
        ><button @click="change(item.id, item.name, index)">改</button>
        <button @click="del(index)">删除</button>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "app",
  data() {
    return {
      id: "",
      name: "",
      indexs: "",
      disabled: false,
      commonBtnInfo: "新增",
      commonBtnInfos: "修改",
      showChangeInfo: false,
      person: [
        {
          id: 1,
          name: "校长",
        },
        {
          id: 2,
          name: "校长1",
        },
        {
          id: 3,
          name: "校长2",
        },
        {
          id: 4,
          name: "校3",
        },
        {
          id: 5,
          name: "校4",
        },
        {
          id: 6,
          name: "校长5",
        },
      ],
    };
  },
  computed: {
    // 查
    filterPerson() {
      let { name, person } = this;
      let arr = [...person];
      if (name.trim()) {
        // 过滤出匹配双向绑定搜索的值
        arr = person.filter((p) => p.name.indexOf(name) !== -1);
      }
      return arr;
    },
  },
  methods: {
    // 增
    newPerson() {
      let newObject = {
        id: this.id,
        name: this.name,
      };
      let person = this.person;
      person.push(newObject);
    },
    // 改
    change(index, name, indexs) {
      this.id = index;
      this.name = name;
      this.showChangeInfo = true;
      this.indexs = indexs;
      this.disabled = true;
    },
    xiugai() {
      this.showChangeInfo = false;
      // 第一个参数是要修改的数据,第二个值是修改当前数组哪一个字段,第三是要修改为什么
      this.$set(this.person[this.indexs], "name", this.name);
      this.id = "";
      this.name = "";
      this.disabled = false;
    },
    // 删除
    del(index) {
      return this.person.splice(index, 1);
    },
  },
};
</script>

<style scoped>
.person {
  text-align: end;
  width: 300px;
}
li {
  list-style: none;
  margin: 40px;
  padding: 40px;
  border: 1px solid yellow;
}
</style>