Skip to main content

Use of custom events in Vue components.

 The parent component uses props to pass data (such as a method) to the child component, and the child component needs to use custom events to pass data back to the parent component! We can use v-on to bind custom events, and then pass them to subcomponents, which will call after receiving the method. Each Vue instance implements the Events interface, that is: use $on(eventName) to listen for events and $emit(eventName) to trigger events.

Ways to use props

//App.vue
<template>
  <div>
    <Son :sendToSon="sendToSon"></Son>
  </div>
</template>
methods: {
  sendToSon(prams){
    console.log(prams)
  }
},
//Son.Vue
<template>
  <div>
    <button @click="sendToFather">Send</button>
  </div>
</template>
<script>
export default {
  name:"Son",
  props:["sendToSon"],
  data () {
    return {
      name: 'hello!!!'
    }
  },
  methods: {
    sendToFather(){
      this.sendToSon(this.name)
    }
  },
}
</script>

Use the ref attribute to complete

//App.vue
<template>
  <div>
    <Son ref="son"></Son>
  </div>
</template>
methods: {
  sendToSon(prams){
    console.log(prams)
  }
},
 mounted() {
    setTimeout(()=>{
      this.$refs.son.$on("fun1",this.sendToSon)
    },2000)
  }
//Son.vue
<template>
  <div>
    <button @click="sendToFather">Send</button>
  </div>
</template>
<script>
export default {
  name:"Son",
  data () {
    return {
      name: 'hello!!!'
    }
  },
  methods: {
    sendToFather(){
      this.$(emit)("fun1",this.name)
    }
  },
}
</script>

Comments

Popular posts from this blog

A simple understanding of ES6 iterators

 What is an iterator?An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed.ES6 created a new traversal command for...of loop, which natively has a data structure with the iterator interface (which can be traversed with for...of). Contains Array, Arguments, Set, Map, String, TypedArray, NodeList. Of course, you can also implement this interface manually, which is convenient for practical use.