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

Destructuring assignment in ES6

 In the past, when we wanted to assign a value to a variable, such as an array type and an object type, to assign a value to a variable, we could only specify the value directly. It is very troublesome to write in this way, but under the ES6 syntax specification, it is allowed to directly extract the required values from arrays and objects according to a certain pattern, and directly assign variables to variables. This method is called Destructuring, which is simple to understand. That is, the left and right sides of the equal sign are equal.

favicon.ico 404 Not Found Causes and Solutions

 What is favicon? It is the abbreviation of Favorites Icon. Its function is that in addition to displaying the corresponding title in the browser's favorites, icons can also be used to distinguish different websites. When I encounter this kind of error, I feel very uncomfortable. There is obviously no problem. Why is a 404 error reported? The following is the solution.