vue-慕课-使用组件改造todoList

前言

在上一节里,我们已经写了一个todoList,下面我将用全局组件和局部组件化把todoList拆分。

1.父组件向子组件传值

全局组件

父组件中相关代码
 Vue.component(
         "TodoList",{
             props:['content'],
             template:"<li>{{content}}</li>"
         }
     )
子组件中相关代码
 <!-- 注意不要忘记加v-bind -->
        <todo-list v-for="item in list" v-bind:content="item"></todo-list>

解析:

  1. 先定义一个全局化的组件TodoListtemplate代表模板,props代表接收从子组件传来的数据,里面是数组的形式。
    注意事项:
  • . 要使用**v-bind:**来绑定数据

局部组件

父组件相关代码
  // 局部组件化
    var todoList = {
        props: ['content'],
        template: "<li>{{content}}</li>"

    }

new Vue中添加components属性

 components:{
            todoList:todoList
        },

注意:

  • components应该是复数

子组件向父组件传值

当点击删除的时候就要用到这个啦,,感觉很麻烦,需要注意的地方也很多。

  1. 首先在template模板中加入点击事件。
        template: "<li @click='handleDelete'>{{content}}</li>",

  1. 在子组件里把handleDelete实现,这里使用this.$emit(“deleteindex”,this.index) 函数,传入父组件中。
handleDelete:function(){
                // alert("子组件"+this.index)
                this.$emit("deleteindex",this.index)
            }
  1. todo-list补充完整。
<todo-list v-for="(item,index) in list"
         v-bind:content="item" :index="index"
         @deleteindex="delete1"
        ></todo-list>

4.最后在父组件中实现delete1,实现删除功能。

 delete1: function(index){
                this.list.splice(index,1)
            }

注意:

  • @后面的一定不要有大写的字母,否则会报错
  • v-bind: 可以简写为 :

写于2020年情人节,祝天下有情人终成眷属


原创文章 73 获赞 79 访问量 33万+

猜你喜欢

转载自blog.csdn.net/qq_41346335/article/details/104312916