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

Use of js array filter() method

 Arrays are frequently used in development, and processing data in arrays is one of the more common and important operations. Therefore, processing data in arrays during development is an important skill. Every developer Everyone should master the operations of arrays, especially for junior developers who have just entered the industry, so be sure to master the relevant skills. This article mainly shares some operations to filter the data in the array, about the use of the filter() method.

ES6 arrow functions

 In ES6, in addition to the new features of let and const, arrow functions are the most frequently used new features. But this feature is not unique to ES6. Arrow functions, as the name suggests, are functions defined using arrows (=>) and belong to a class of anonymous functions. It allows us to write smaller function syntaxes. The code of arrow functions is simpler and more flexible to write.