1. $attrs
官方解释:
简言之,$attrs相当于跨组件传参的桥梁 ,
1.在版本2.4以前,默认情况下父组件传递的不被子组件props接受的属性,将会“回退”且作为普通的HTML特性应用在子组件的根元素上。如下列的例子
组件one:
<template>
<div>
<two :name='name' :age='age' />
</div>
</template>
<script>
import two from './two'
export default {
components: {
two
},
data () {
return {
name: 'jdd',
age: '20'
}
}
}
</script>
组件two:
<template>
<div> <!-- props未接受的age属性将会绑定到这里 -->
这是two组件
</div>
</template>
<script>
export default {
props: ['age'],
}
</script>
如下图:
2.想阻止这一默认行为。vue2.4中新增选项inheritAttrs inheritAttrs的默认值为true, 将inheritAttrs的值设为false, 这些默认的行为会禁止掉。但是通过实例属性$attrs ,可以将这些特性生效,且可以通过v-bind 绑定到子组件的非根元素上。
官方解释:
one组件
<template>
<div>
<two :name='name' :age='age' v-bind='$attrs' />
</div>
</template>
<script>
import two from './two'
export default {
components: {
two
},
data () {
return {
name: 'jdd',
age: '20'
}
}
}
</script>
two组件:
<template>
<div>
这是two组件--这是通过$attrs接收的参数{{this.$attrs}}
</div>
</template>
<script>
export default {
inheritAttrs: false, //阻止不被props接受的属性绑定到根元素上。
props: ['age'],
}
</script>
2.下面讲一下如何跨组件传递参数
原理很简单,不被props接收的组件想传递到更深层次的组件里使用就用$attrs ‘搭桥’。
场景:two组件不需要one组件传递的 name属性 但是 three 、four组件需要。下面上代码演示$attrs 的传递
one组件:
<template>
<div>
one组件
<two :name='name' :age='age' />
</div>
</template>
<script>
import two from './two'
export default {
components: {
two
},
data () {
return {
name: 'jdd',
age: '20'
}
}
}
</script>
two组件:
<template>
<div>
这是two组件
<three v-bind='$attrs' />
</div>
</template>
<script>
import three from './three'
export default {
inheritAttrs: false,
props: ['age'],
components: {
three
}
}
</script>
three组件
<template>
<div>
这是第三层组件
<four v-bind='$attrs' />
<!-- 这里如果想使用父组件传递的属性 直接this.$attrs接收就行 -->
</div>
</template>
<script>
import four from './four'
export default {
// 这里未使用inheritAttrs 阻止默认行为
components: {
four
}
}
</script>
four组件:
<template>
<div>
这是第四层组件------第一层组件的消息{{this.$attrs}}
</div>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
如下图:
本来想写 $attrs和$listeners的,罗里吧嗦一大堆。再开一篇吧。如有不对的地方欢迎指正。