The use of attrs and listeners in vue2 (component communication)

The use of attrs and listeners in vue2 (component communication)

Vue2.4.0 new $attrsand $listenerattribute

  • attrs

    When a component does not declare any props, $attrsit will contain all parent scope bindings (except class and style), and can be v-bind="$attrs"passed to internal components, generally used on child elements of child components

  • listener

    Contains v-on event listeners from the parent scope (without the .native decorator). It can be v-on="$listeners"passed to internal components via

<template>
  <div class="page-all">
    a-page
    <B :msg1="msg1" :msg2="msg2" @method1="handleClick" @method2="handleClick"></B>
  </div>
</template>

<script>
import B from "./B.vue"

export default {
  name: "A",
  data() {
    return {
      msg1: "msg1",
      msg2: "msg2",
    }
  },
  components: {B},
  methods: {
    handleClick() {
      console.log('a click')
    }
  },
  mounted() {},
}
</script>
<template>
  <div class="page-all">
    b-page
    <p>$attrs: {
   
   { $attrs }}</p>
    <div @click="handleAClick">handleAClick: {
   
   { msg1 }}</div>
    <C v-bind="$attrs" v-on="$listeners"></C>
  </div>
</template>

<script>
import C from "./C.vue"

export default {
  name: "B",
  props: ['msg1'],
  data() {
    return {}
  },
  components: {C},
  methods: {
    handleAClick() {
      console.log('b click')
      this.$emit('method1')
    }
  },
  mounted() {},
}
</script>
<template>
  <div class="page-all">
    c-page
    <p>$attrs: {
   
   { $attrs }}</p>
    <div @click="handleCClick">handleCClick: {
   
   { msg1 }}{
   
   { msg2 }}</div>
  </div>
</template>

<script>
export default {
  name: "C",
  props: ['msg1', 'msg2'],
  data() {
    return {}
  },
  components: {},
  methods: {
    handleCClick() {
      console.log('c click')
      this.$emit('method2')
    }
  },
  mounted() {},
}
</script>
  • Summarize

    $attrspropsIt is to send the parent component to the grandchild component that is not received listenerby the component , but to @方法inherit the parent component to the grandchild component

Guess you like

Origin blog.csdn.net/qq_23858785/article/details/130565065