This is the 30th day of my participation in the August Text Challenge.More challenges in August
Define custom events
In VUE we often use built-in VUE events such as Click,mouseover… When a parent component passes data to a child component, it uses props, but if the child component passes data back, it needs to use custom events
Child components (school. Vue)
<template>
<div>
<h3>school name:{{name}}</h3>
<h3>school address:{{address}}</h3>
<button @click="sendSchoolName" >Get school name</button>
<button @click="unbind">Unbundling event</button>
</div>
</template>
<script>
export default {
data() {
return {
name:Chimp Land.address:'Flower and Fruit Hill'}},methods: {sendSchoolName(){
// Triggers a custom event
this.$emit('badspider'.this.name,2.3.4.1.4.2)},unbind(){
// Only one custom event can be unbound
this.$off('badspider')
// Unbind multiple custom events
// this.$off(['badspider','demon'])
// Unbind all custom events
// this.$off()}}}</script>
Copy the code
The parent component
<template>
<div id="app">
<school @badspider='demon'></school>
</div>
</template>
<script>
import school from './components/school'
export default {
name: 'App'.components:{student,school},
data(){
return {
msg:'badspider'}},methods: {demon(name,... params){
console.log('school name is:',name,params); }}},</script>
Copy the code
Let’s take a look at this code. First you define an event, just as you would bind an event with v-on: badSpider =” XXX “, except that the name of the event is not click, but your own custom name. XXX is a callback function. The callback function will be called
$emit(‘ badSpider ‘); $emit(‘badspider’); $emit(‘badspider’); $emit(‘badspider’,name,1,2,3,4); $emit(‘badspider’,name,1,2,3,4); Params), which will receive a name and an array
Custom event unbinding
$off(‘badspider’) can be used to unbind a custom event when it is not needed. If you want to unbind a single event, use $off(‘badspider’). If you want to unbind multiple events, Off ([‘badspider’,’ XXX ‘,’ XXXX ‘] is an array of arguments, or $off() is used to unbind all custom events