Vue组件之实现自定义事件
自定义事件本质是由子组件向父组件传递信息
1、子组件,触发click点击事件时,通过$emit(...)触发父组件里自定义的事件defclick
<template> <div role="alert" :class="['el-alert',changeAlert,'is-center','is-light']"> <i :class="['el-alert__icon',changeIcon]"></i> <div class="el-alert__content"> <slot name="title"> <span class="el-alert__title">{{title}}</span> </slot> <i class="el-alert__closebtn el-icon-close" @click="clickHandle"></i> </div> </div> </template> <script> export default { methods:{ clickHandle(){ this.$emit('defclick'); } } } </script>
2、父组件,定义自定义事件defclick对应的处理函数,接收来自子组件的信息
<template> <div id="app"> <alert type="success" title="这是一段成功提示的信息" @defclick='clickHandle' /> <alert @defclick="clickHandle" /> </div> </template> <script> import alert from '@/components/alert'//引入子组件 export default { name: 'App', components: {//注册 alert }, methods: { clickHandle() { console.log('test') } } } </script>