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

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.

Js uses recursive way to traverse the dom tree to dynamically create element nodes

 What is a dom tree? In short, DOM is the Document Object Model, which provides a structured representation for documents and defines how to access the document structure through scripts. DOM is composed of nodes. After the HTML is loaded, the rendering engine will generate a DOM tree in memory based on the HTML document. This article uses a small case to traverse the dom tree recursively. The core of the method is to determine whether the incoming data is an array, and then traverse the root node. Note that there must be an end condition when using recursion.