vue实现添加删除列表

通过子父类之间的传值进行操作

效果:

父类:

//注意引入的位置

<template>
  <div>
    <input v-model="inputValue"/>
    <button @click="handleSubmit">提交</button>
    <ul>
      <Item
        v-for="(item,index) of list"
        :key="index"
        :content="item"
        :index="index"
        @delete="handleDelete"
      ></Item>
    </ul>
  </div>
</template>

<script>
  //注意引入的位置
  import Item from './Item'

  export default {
    name: "Test",
    components: {Item},
    data() {
      return {
        list: [],
        inputValue: '',
      }
    },
    methods: {
      handleSubmit() {//添加元素
        this.list.push(this.inputValue);
        this.inputValue = '';
      },
      handleDelete(index) {//响应子类传递的事件和点击条目的值
        this.list.splice(index, 1)
      },
    },
  }
</script>

<style scoped>

</style>

子类组件

<template>
  <li @click="handleDelete">{{content}}</li>
</template>

<script>
  export default {
    props: ['content', 'index'],
    methods: {
      handleDelete() {
        //传递delete事件给父类
        this.$emit('delete', this.index)
      },
    },
  }
</script>

<style scoped>

</style>

。。。

猜你喜欢

转载自blog.csdn.net/dianziagen/article/details/88078600