vue组件之间传值很多,父与子传值用的最多的是 e m i t 和 p r o p s , 如 果 多 层 级 传 值 可 以 用 emit 和props,如果多层级传值可以用 emit和props,如果多层级传值可以用attrs,$listeners
**$attrs:
**包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 笼统的说是继承属性
$listeners:
包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 通俗理解就是继承父组件的事件
父组件
//father
<template>
<div>
<Child @reviewInfo="reviewInfo" :row="row"></Child>
</div>
</template>
<script>
import Child from './child'
export default{
data(){
row:{id:1,class:'班级6'}
},
components:{
Child
},
methods:{
reviewInfo(){
console.log("获取父组件事件!!!")
}
}
}
</script>
子组件
<template>
<div class="child" style="height: 300px;width:100%">
<GrandChild v-bind="$attrs" v-on="$listeners"></GrandChild>
</div>
</template>
<script>
import GrandChild from './grandChild'
export default{
inheritAttrs:true, //默认是true,继承父组件的属性在子组件的根元素上显示
data(){
return{
tableData:[]
}
},
components:{
GrandChild
},
created(){
console.log(this.$listeners,'listeners')
},
methods:{
}
}
</script>
孙子组件
<template>
<div class="grand-child" style="width:300px;height:300px">
<el-button @click="clickHandle">点击</el-button>
</div>
</template>
<script>
export default {
created() {
console.log(this.$listeners, 'grand')
console.log(this.row,'row')
},
props:{
row:{
type:Object,
default:()=>{}
}
},
methods: {
clickHandle() {
// 控制台打印的grandChild 获取父组件事件
console.log('grandChild')
this.$emit('reviewInfo')
}
}
}
</script>