Vue——自定义事件

本文介绍了Vue中自定义事件的概念,用于解决组件间通信问题。通过自定义事件,可以实现对Vue实例数据的操作。内容包括Vue的双向数据绑定特性如何在组件间起到桥梁作用,以及一个具体的自定义事件使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue——自定义事件

​ 由于Vue中的其他组件无法使用到Vue实例中的数据,可以通过自定义事件完成对Vue实例中数据的一些操作,具体图解如下:

在这里插入图片描述

其中,由于Vue中具有的数据双向绑定的特性,使得前端可以作为组件与实例的桥梁,利用自定义事件实现一些功能。

示例代码:

//前端
<div id="app" >
    <todo>
        <todo-title slot="todo-title" :title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in items" :item="item"
       :index="index" :key="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>
</div>
//Vue
<!--导入Vue-->
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
<script type="text/javascript">

    //slot:插槽
    Vue.component("todo",{
        template: '<div>\
                    <slot name="todo-title"></slot>\
                    <ul>\
                    <slot name="todo-items"></slot>\
                    </ul>\
                    </div>'
    });
    Vue.component("todo-title",{
        props:['title'],
        template: '<div>{{title}}</div>'
    });
    Vue.component("todo-items",{
        props: ['item','index'],
        //记得button绑定事件
        template:'<li>{{index}}---{{item}}<button @click="remove">删除</button></li>',
        methods:{
            remove:function(index){
                this.$emit('remove',index);
    }
        }
    });
    var vm = new Vue({
        el:'#app',
        data: {
            title: "书籍列表",
            items:['Java','Math','English']
                },
        //methods不要放进data里!!
        methods: {
            removeItems:function (index){
                console.log("删除了"+this.items[index]);
                this.items.splice(index,1);
            }
        }
    });
</script>

关于V-bind key="":

}
    }
});

**关于V-bind key="":**

>一句话,**key的作用主要是为了高效的更新虚拟DOM**。另外vue中在使用相同标签名元素的过渡切换时,也会使用到key属性,其目的也是为了让vue可以区分它们。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值