vue組件通信之$attr和$listenn


  1. $attrs
    場景:如果父傳子有很多值,那么在子組件需要定義多個 props
    解決:$attrs獲取子傳父中未在 props 定義的值
// 父組件
<home title="這是標題" width="80" height="80" imgUrl="imgUrl"/>

// 子組件
mounted() {
  console.log(this.$attrs) //{title: "這是標題", width: "80", height: "80", imgUrl: "imgUrl"}
},

注意:相對應的如果子組件定義了 props,打印的值就是剔除定義的屬性

props: {
  width: {
    type: String,
    default: ''
  }
},
mounted() {
  console.log(this.$attrs) //{title: "這是標題", height: "80", imgUrl: "imgUrl"}
},

2.$listeners
場景:子組件需要調用父組件的方法
解決:父組件的方法可以通過 v-on="$listeners" 傳入內部組件——在創建更高層次的組件時非常有用

// 父組件
<home @change="change"/>

// 子組件
mounted() {
  console.log(this.$listeners) //即可拿到 change 事件
}

如果是孫組件要訪問父組件的屬性和調用方法,直接一級一級傳下去就可以
摘自https://segmentfault.com/a/1190000020620972,詳細參考跳轉該內容


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM