this.$attrs包含所有父组件传递过来的属性(不包括被prop识别的和 class 、 style )。 this.$listeners包含所有父组件传递过来的事件监听组成的对象 (不含 .native 修饰器的v-on 事件监听器。)
<template>
<div>
<HintButton :h='aa' name='kk' age="99" @hh="test"></HintButton>
</div>
</template>
<script>
import HintButton from './HintButton.vue'
export default {
name: "AttrsListeners",
data() {
return {
aa:'22'
}
},
components:{
HintButton
},
methods: {
test(){
}
},
}
</script>
<template>
<div></div>
</template>
<script>
export default {
name: "HintButton",
mounted() {
console.log(this.$attrs, this.$listeners);
},
};
</script>
控制台打印 {h: “22”, name: “kk”, age: “99”} {hh: ?}
如果子组件用props接收,那么该属性this.$attrs里就不会出现
<template>
<div></div>
</template>
<script>
export default {
name: "HintButton",
props: ["h"],
mounted() {
console.log(this.$attrs, this.$listeners);
},
};
</script>
此时控制台打印 {name: “kk”, age: “99”} {hh: ?}
下面来进行简单的组件封装
<template>
<div>
<HintButton type="primary" size="mini"></HintButton>
</div>
</template>
<script>
import HintButton from "./HintButton.vue";
export default {
name: "AttrsListeners",
components: {
HintButton,
},
};
</script>
<template>
<div>
<a href="javascript:;" :title="title">
<el-button v-bind="$attrs" v-on="$listeners"></el-button>
</a>
</div>
</template>
<script>
export default {
name: "HintButton",
props: ["title"]
};
</script>
|