1. 程式人生 > 實用技巧 >【vue開發】v-bind="$attrs" v-on="$listeners" 多層元件監聽

【vue開發】v-bind="$attrs" v-on="$listeners" 多層元件監聽

多級元件通訊,用vuex太重,props太麻煩。

vue 2.4 版本提供了另一種方法,使用 v-bind=”$attrs”, 將父元件中不被認為 props特性繫結的屬性傳入子元件中,通常配合 interitAttrs 選項一起使用。

<top>
    <center>
        <bottom>
        </bottom>
    </center>
</top>

需求:top和bottom間進行通訊

  1. props和$emit,需要center作為中轉

  2. vuex,確定是全域性狀態?

    <top @getDataList ="getDataList" :yes="123"><top>
     
    //
    .native綁原生事件是沒用的 <center v-on="$listeners" v-bind="$attrs"></center> //在bottom元件中,可以直接呼叫getDataList這個方法 export default { name: 'index', props: ['yes'], inheritAttrs: false, methods: { doClick(data) { console.log(this.yes) // 123, top元件中傳遞下來的props(center中props宣告過的除外)
    this.$emit('getListData', data) } } } // inheritAttrs:預設值true,繼承所有的父元件屬性(除props的特定繫結)作為普通的HTML特性應用在 // 子元件的根元素上,如果你不希望元件的根元素繼承特性設定inheritAttrs: false,但是class屬性會繼承 </script>