Vue---todolist的组件化编程

主组件

<template>
  <div>
     
        <input type="text" v-model="inputValue">
        <button @click="submitClick">提交</button>
      
      <ul>
        <todo-item v-for="(item,index) of list"
        :key="index"
        :content="item"
         :index="index"
        @delete="deleteClick"
        ></todo-item>
      </ul>
  </div>
</template>

<script>
 import ToDoItem from './components/ToDoItem.vue'


export default {
  components:{
    "todo-item":ToDoItem
  },
  data: function() {
    return{
      inputValue:" ",
      list:[],
    }
  },
  methods:{
    submitClick(){
      this.list.push(this.inputValue),
      console.log(this.list),
      this.inputValue=" "
    },
  deleteClick(index){
    this.list.splice(index,1)
  }
  },
}
</script>

子组件

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

<script>  
       
export default {
  props:['content','index'],
  data: function() {
    return{       
         
    }
  },
  methods:{
     handleDelete(){
       this.$emit("delete",this.index)
     }
  },
}
</script>

这个删除功能的实现逻辑:
1、由主组件通过:index="index"向子组件发送index属性,告诉子每个子组件自己的编号,子组件通过props[“index”]
接收这个属性
2、为了让每个子组件都能够有删除功能,应给每个子组件添加点击事件@click:‘handleDelete’
handleDelete将触发子组件的方法this.$emit(“delete”,index),由被点击的子组件向主组件的delete事件发送参数index
3,主组件接收子组件发来的index值,并触发delete事件
delete(index){
this.list.splice(index,1)//删除下标为index起的一个元素
}
一旦list中的index对应的元素被删除,那么这个子组件也就被删除了,至此完成删除功能。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值