簡單聊聊vue2.x的$attrs和$listeners

$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

總結

到此這篇關於vue2.x的$attrs和$listeners的文章就介紹到這瞭,更多相關vue2.x $attrs和$listeners內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: