關於 vue2.x 的 $attrs 和 $listeners

蘆薈柚子茶發表於2022-03-09

$attrs

$attrs 用於多層次元件傳遞引數(元件標籤的attribute,class和style除外),爺爺輩元件向孫子輩元件傳遞引數(注:引數不能被父輩prop識別,一旦被父輩prop識別且獲取,則孫子輩元件不能獲取到該引數

寫法如下:(注:v-bind不能用簡寫 :

<grand-son v-bind="$attrs" />

下面舉個例子:

爺爺(GrandFather)向父親(Father)傳遞一個 msg1

向孫子(GrandSon)傳遞一個 msg2,孫子會一併接收 msg1(然而被父親接走了,所以孫子收不到 msg1

<!-- GrandFather.vue -->
<template>
  <div>
    GrandFather:
    <father :msg1="msg1" :msg2="msg2" />
  </div>
</template>

<script>
import Father from './Father.vue'
export default {
  components: { Father },
  data() {
    return {
      msg1: 'msg1',
      msg2: 'msg2'
    }
  }
}
</script>
<!-- Father.vue -->
<template>
  <div>
    Father: {{ msg1 }}
    <grand-son v-bind="$attrs" />
  </div>
</template>

<script>
import GrandSon from './GrandSon.vue'
export default {
  components: { GrandSon },
  props: ['msg1']
}
</script>
<!-- GrandSon.vue -->
<template>
  <div>GrandSon: {{ msg1 }}{{ msg2 }}</div>
</template>

<script>
export default {
  props: ['msg1', 'msg2']
}
</script>

介面現實結果:

GrandFather:
Father: msg1
GrandSon: msg2

$listeners

$listeners 用於多層次元件傳遞事件監聽器,爺爺輩元件向父輩、孫子輩、曾孫子輩……元件傳遞事件(與 $attrs 不同,不存在半路被攔截的情況)

寫法如下:(注:v-on 不能用簡寫 @,雖然不報錯,但是也不生效)

<grand-son v-on="$listeners" />

下面繼續使用 爺爺-> 父親 -> 孫子 的栗子:

爺爺(GrandFather)給父親(Father)繫結一個 click 事件

父親通過點選 div 觸發 click 事件,同時向孫子(GrandSon)傳遞 $listeners

<!-- GrandFather.vue -->
<template>
  <div>
    GrandFather:
    <father :msg1="msg1" :msg2="msg2" @click="handleClick" />
  </div>
</template>

<script>
import Father from './Father.vue'
export default {
  components: { Father },
  data() {
    return {
      msg1: 'msg1',
      msg2: 'msg2'
    }
  },
  methods: {
    handleClick() {
      console.log('trriger click')
    }
  }
}
</script>
<!-- Father.vue -->
<template>
  <div>
    <div @click="handleFatherClick">Father: {{ msg1 }}</div>
    <grand-son v-bind="$attrs" v-on="$listeners" />
  </div>
</template>

<script>
import GrandSon from './GrandSon.vue'
export default {
  components: { GrandSon },
  props: ['msg1'],
  methods: {
    handleFatherClick() {
      console.log('father click')
      this.$emit('click')
    }
  }
}
</script>
<!-- GrandSon.vue -->
<template>
  <div @click="handleSonClick">GrandSon: {{ msg1 }}{{ msg2 }}</div>
</template>

<script>
export default {
  props: ['msg1', 'msg2'],
  methods: {
    handleSonClick() {
      console.log('grandson click')
      this.$emit('click')
    }
  }
}
</script>

介面:

GrandFather:
Father: msg1
GrandSon: msg2

點選 Father: msg1,控制檯顯示:

father click
trriger click

點選 GrandSon: msg2,控制檯顯示:

grandson click
trriger click

相關文章