Vue组件父子之间自定义事件
父组件使用props传递数据给子组件,子组件怎么跟父组件通信呢?这时,Vue的自定义事件就派上用场了
示例代码
<div id="zjw1">
    <span>CQNU--重庆ZJW--同学</span>
    <input placeholder="张俊Wei请输入内容" v-model="Value">
    <button @click="add">添加</button>
    <ul>
        <todo-item
                v-for="(item,index) in list"
                :key="index"
                :content="item"
                :index="index"
                @del="Delete">
        </todo-item>
    </ul>
    <span>当前有{{ list.length}}项未完成</span>
</div>
<template id="com">
    <li>{{content}}  <button @click="zjw">删除</button></li>
</template>
<script>
    Vue.component('TodoItem',{
        props:['content','index'],
        template:`#com`,
        methods:{
            zjw:function(){
                this.$emit('del',this.index)
            }
        }
    })
    new Vue({
        el:"#zjw1",
        data:{
            Value:'',
            list:[],
        },
        methods:{
            add:function(){
                this.list.push(this.Value);
                this.Value='';
            },
            Delete:function(i){
                this.list.splice(i,1);
            }
        }
    })
</script>
简单分析
我们创建了一个全局组件TodoItem将其中的template中button绑定一个自定义事件del
<button @click="zjw">删除</button>
            zjw:function(){
                this.$emit('del',this.index)
            }
在父组件中@del="Delete"就可以转到vue的methods中的Delete方法,从而进行删除了。
Delete:function(i){
                this.list.splice(i,1);
            }
同时用list.length来记录list中的个数
<span>当前有{{ list.length}}项未完成</span>
效果演示

 



















