属性透传:同时使用两种或以上的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>