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

vue routing global guard beforeEach and afterEach

 Global routing front guard (beforeEach) This function is used the most. Its function is to perform permission-related verification before routing jumps. This function contains three parameters: to: the object of the target route that is about to enter; from: the route that the current route is leaving; next: confirm the release. It can be used to log in and register, to determine whether there is a token before logging in, and release if it exists. , if it does not exist, it will not be released. The post routing guard (afterEach), its role is to trigger after the routing jump.

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.