1.应用场合
多层级组件之间传参可以使用$attrs, 如果使用普通的父子组件传参prop
和$emit,
每一级组件都需要进行接收,然后向下传递,就很麻烦。
在使用$attrs时,如果组件中不使用props进行接收,这些参数将会作为此组件的HTML元素特性。如果这个组件中使用了props进行了接收,那么被接收的参数将不会向下传递。
inheritAttrs: false
的含义是不希望本组件的根元素继承父组件的attribute,同时父组件传过来的属性(没有被子组件的props接收的属性),也不会显示在子组件的dom元素上,但是在组件里可以通过其$attrs可以获取到没有使用的注册属性。
$attrs 是传递参数变量的
$listenters 是传递函数的
2.直接上代码
组件结构为 grandFatherView > fatherView > childView
grandFatherView组件中:
<template>
<div class='grand-father-view'>
<fatherView :row="row" :column="column" @friendly="friendly" @diss="diss"> </fatherView>
</div>
</template>
<script>
import fatherView from './fatherView.vue'
export default {
components:{ fatherView },
data() {
return {
isOpen: false,
row: {name: 'nicholas', age: 23},
column:{sex: '男', id : 12},
diss: ()=>{
console.log("diss")
},
friendly: ()=>{
console.log("friendly")
}
}
}
}
<script>
fatherView组件中,拦截row参数,column将通过$attrs继续传递;
<template>
<div class='father-view'>
<p>{
{ row.name }}</p>
<p>{
{ row.age }}</p>
<childView v-bind="$attrs" v-on="$listeners"> </childView >
</div>
</template>
<script>
import childView from './childView .vue'
export default {
inheritAttrs: true, // 浏览器F12调试可以看到 此组件的根元素,:column="[objcet, object]"
components:{ childView },
data() {
return { }
},
props:{
row: {
type: object,
default: () => {}
}
},
mounted(){
this.$listeners.friendly()
}
}
<script>
childView组件中,接收column参数
<template>
<div class='child-view'>
<p>{
{ column.sex }}</p>
<p>{
{ column.id }}</p>
</div>
</template>
<script>
export default {
data() {
return { }
},
props:{
column: {
type: object,
default: () => {}
}
},
mounted(){
this.$listeners.diss()
this.$listeners.friendly()
}
}
<script>