$attr是一个对象,它包含了父组件传递给子组件但子组件没有显式声明的props
父亲传数据到孙子
<template>
<child :name="name" :age="age" :infoObj="infoObj" />
</template>
<script>
import Child from '../components/child.vue'
export default {
name: 'father',
components: { Child },
data () {
return {
name: 'Lily',
age: 22,
infoObj: {
from: '上海',
job: 'policeman',
hobby: ['reading', 'writing', 'skating']
}
}
}
}
</script>
<template>
<grand-son :height="height" :weight="weight" v-bind="$attrs" />
</template>
<script>
import GrandSon from '../components/grandSon.vue'
export default {
name: 'child',
components: { GrandSon },
props: ['name'],
data() {
return {
height: '180cm',
weight: '70kg'
};
},
created() {
console.log(this.$attrs);
// 结果:age, infoObj, 因为父组件共传来name, age, infoObj三个值,由于name被 props接收了,所以只有age, infoObj属性
}
}
</script>
<template>
<div>
{{ $attrs }}
<div>
</template>
<script>
export default {
props: ['weight'],
created() {
console.log(this.$attrs); // age, infoObj, height
}
}
</script>