今天在官网看到组件传/取值除了provide/inject,emit....还可以使用$attrs和$listeners
于是看官方文档:
$attrs
包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (`class` 和 `style` 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (`class` 和 `style` 除外),并且可以通过 `v-bind="$attrs"` 传入内部组件——在创建高级别的组件时非常有用.
简单来说:接收除了props声明外的所有绑定属性(class、style除外
$listeners
包含了父作用域中的 (不含 `.native` 修饰器的) `v-on` 事件监听器。它可以通过 `v-on="$listeners"` 传入内部组件——在创建更高层次的组件时非常有用
简单来说
接收除了带有.native事件修饰符的所有事件监听器
如下示例:
parent.Vue
<template>
<div style="height:5000px;background:#fff;">
<h5>子父组件传值(子组件改变prop值)</h5>
<vChild :msgVal='msg' :age='age' :sex='sex' @changeMsg='changeMsg'></vChild>
</div>
</template>
<script>
import vChild from './vChild.vue'
export default {
components:{
vChild
},
data(){
return{
msg:'这是父组件哦',
age:12,
sex:'女'
}
},
methods:{
changeMsg(param){
alert('555')
}
}
}
</script>
Child.vue
<template>
<div style="height:5000px;background:#fff;text-align:left;">
<h5>子组件</h5>
props:{{mag1}}
<el-button @click="changeProps"> Start</el-button>
<br>
<span>
<!-- 孙组件绑定attrs -->
<Grandson v-bind="$attrs" height='88'></Grandson>
</span>
<!-- msg2:{{msg2}} -->
</br>
<!-- <h5>初始值:{{num}}</h5>
<el-button @click="changeCom">Start</el-button>
</br>
<h5>Computed 响应data值:{{Comnum}}</h5>
</br>
<h5>Computed 不会响应不存在data中的值:{{NowTime}}(获取当前时间戳)</h5> -->
</div>
</template>
<script>
import Grandson from './grandSon'
export default {
props:['msgVal'],
components:{
Grandson
},
data(){
return{
mag1:'',
num:55,
}
},
computed:{
Comnum(){
let total = this.num*10
return total;
},
NowTime(){
return Date.now();
},
msg2(){
return this.msgVal
},
},
watch:{
Now(newVal){
console.log(newVal)
}
},
methods:{
changeProps(){
// console.log('111111')
this.mag1 = '改变了props',
this.$emit('changeMsg','333')
},
changeCom(){
this.num+=1
},
},
mounted(){
this.mag1 = this.msgVal;
console.log(this.$attrs) // 接受到父组件除props属性 {'age':12,'sex':'女'}
console.log(this.$listeners.changeMsg()) //也可以相当于调用该方法 {changeMsg:f}
},
}
grandSon.vue
<template>
<div>
<h1>孙组件</h1>
</div>
</template>
<script>
export default {
data(){
return{
}
},
mounted(){
console.log(this.$attrs) //{height:'88',age:12,sex:'女'}接收到祖父组件的属性(除props)以及本属性
}
}
</script>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。