组件自定义事件
内置事件:是给html元素用的,比如span、div等标签,不是组件。
组件自定义事件:自己定义事件三要素,包含事件名也就是事件类型,事件源,事件回调函数,组件内部自己设计事件触发的条件就是组件自定义事件。也是一种组件间的通信方式,适用于子组件给父组件进行传递数据。
组件自定义事件的使用
用v-on指令给组件定义事件名,然后在methods中绑定事件回调函数。在使用自定义事件的组件中,自己设定的某个条件成立了就调用触发组件自定义事件的函数this.$emit(),第1个参数是触发的事件类型也就是定义的事件名,剩下的额外的参数都会传递给事件监听器的回调函数,可选。
this.$emit(event: string, ...args: any[])作用就是在当前组件触发一个自定义事件。
<template>
<div class="father">
<button @click="fn">触发内置事件</button>
<h1>组件自定义事件</h1>
<son @myevent="fm"></son>
</div>
</template>
<script>
// 1.引入子组件
import son from "@/components/son.vue";
export default {
methods: {
fn(){
console.log("内置点击事件触发");
},
fm(){
// son组件是事件源,myevent是son组件绑定的事件类型,fm是事件回调函数
// fm是在myevent事件触发了就运行,myevent事件的触发条件由son组件内部自己设计。
console.log("组件自定义事件触发",arguments)
}
},
components:{
son
}
};
</script>
<style scoped>
.father {
width: 700px;
background-color: purple;
}
</style>
<template>
<div class="son">
<h2>son组件</h2>
<p>{{num}}</p>
<button @click="add">点击让值加1</button>
</div>
</template>
<script>
export default{
data() {
return {
num:0
}
},
methods: {
add(){
this.num++;
}
},
watch:{
num(val){
if(val==6){
// 触发组件自定义事件
this.$emit("myevent","son组件中的数字增加到6了");
}
}
},
mounted() {
this.$emit("myevent");
},
}
</script>
<style scoped="scoped">
.son {
width: 400px;
background-color: gold;
margin: 20px;
}
</style>
组件自定义事件名是原生的内置事件触发的也是原生的内置事件
组件自定义事件名是原生的内置事件触发的也是原生的内置事件就需要在组件的自定义事件名后跟一个.native修饰词。
.native是用来在父组件中给子组件绑定一个原生的事件,就将子组件当成了普通的HTML标签看待
<template>
<div class="father">
<button @click="fn">触发内置事件</button>
<h1>组件自定义事件</h1>
<son @click="fm"></son>
<!-- 该事件绑定在child组件的根元素,只要点击child组件中的任何地方都会触发事件回调函数fg -->
<child @click.native="fg"></child>
</div>
</template>
<script>
// 1.引入子组件
import son from "@/components/son.vue";
import child from "@/components/child.vue";
export default {
methods: {
fn(){
console.log("内置点击事件触发");
},
fm(){
console.log("组件自定义事件触发");
},
fg(){
console.log("点击child组件就会触发");
}
},
components:{
son,
child
}
};
</script>
<style scoped>
.father {
width: 700px;
background-color: purple;
}
</style>
<template>
<div class="son">
<h2>son组件</h2>
<button @click="add">点击触发组件自定义事件</button>
</div>
</template>
<script>
export default{
methods: {
add(){
this.$emit("click")
}
}
}
</script>
<style scoped="scoped">
.son {
width: 400px;
background-color: gold;
margin: 20px;
}
</style>
<template>
<div class="childbox">
<h3>child组件</h3>
<p>child组件的内容</p>
</div>
</template>
<script>
export default {
}
</script>
<style>
.childbox{
width: 200px;
background-color: rgb(24, 183, 211);
cursor: pointer;
}
</style>