明天在官网看到组件传/取值除了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>
https://www.cnblogs.com/chanw...(具体请看)