vue2屬性與事件透傳

屬性透傳:同時使用兩種或以上的v-bind 
v-bind="$attrs"  v-bind="$props"  //報錯: 屬性重復
v-bind="{...$props, ...$attrs}"   // 可以成功執行

事件透傳:
v-on="$listeners"

$props是子組件child.vue的props內的屬性對象
$attrs是父組件傳子組件傳遞的屬性對象
$listeners子組件向父組件回調的函數

父組件parent.vue

<template>
  <div class="parent" data-desc="父組件">
    <child aaa="111" bbb="222" :lazy="true" :load="load" @change="()=>{}"></child>
  </div>
</template>

<script>
import child from "./child.vue";//引入子組件
export default {
  name: "parent",
  components: { child },
  data() {
    return {};
  },
  methods: {
    load() {},
  },
};
</script>

子組件child.vue

<template>
  <div class="parent" data-desc="子組件">
    <div style="padding: 20px">{{ $props }}</div>
    <div style="padding: 20px">{{ $attrs }}</div>
    <!-- 向element-ui的table組件傳遞屬性 -->
    <el-table v-bind="{ ...$props, ...$attrs }" v-on="$listeners"></el-table>
  </div>
</template>

<script>
export default {
  name: "child",
  props: {
    sss: {
      type: String,
      default: "888",
    },
    height: {
      type: Number,
      default: 300, 
    }
  },
  data() {
    return {};
  },
  mounted() {
    console.log("this.$attrs: ", this.$attrs);//輸出:{aaa: "111", bbb: "222", lazy: true, load: function () {}}
    console.log("this.$props: ", this.$props);//輸出:{sss: "888", height: 300}
    console.log("this.$listeners: ", this.$listeners);//輸出:{change: function () {}}

    this.$emit("change",null);
  },
  methods: {},
};
</script>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容