2019-04-10父子组件的交互

2019-04-10  本文已影响0人  泡沫双鱼座

父组件通过属性的方式向子组件传递参数(数据)。

子组件通过发布订阅模式向父组件,子组件发布一个事件,父组件恰好之前就已经订阅了这个事件。

<div class="todoList">

    <input type="text" placeholder="请输入内容" v-model="val" />

    <button type="button" @click="handles()">添加</button>

    <ul>

        <todo-item v-for="(item,index) of list" :key="index"

        :content="item" :index="index" @delete="handleDel()"></todo-item>

    </ul>

</div>

js:

Vue.component('todo-item',{

    template:'<li>{{content}}<button @click="handleClick()">删除</button></li>',

    props:['content','index'],

    methods:{

        handleClick(){

            this.$emit('delete',this.index)

        }

    }

})

new Vue({

    el: ".todoList",

    data:{

        val: '',

        list: []

    },

    methods:{

        handles(){

            //this.list.push(this.val);

            this.list.unshift(this.val);

            this.val = '';

        },

        handleDel(index){

            this.list.splice(index,1);

        }

    }

})

上一篇 下一篇

猜你喜欢

热点阅读