屬性透傳:同時使用兩種或以上的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>