$attrs
的使用 vue$attrs
是在vue的2.40版本以上添加的。inheritAttrs: false
的含义是不希望本组件的根元素继承父组件的attribute,同时父组件传过来的属性(没有被子组件的props接收的属性),也不会显示在子组件的dom元素上,但是在组件里可以通过其$attrs可以获取到没有使用的注册属性, “inheritAttrs: false`是不会影响 style 和 class 的绑定 $attrs
的使用示例(父组件的列表行数据传递给孙子组件展示)<template>
<div>
<el-table :data='list'>
<el-table-column
prop="name"
label="姓名"
></el-table-column>
<el-table-column
prop="study"
label="学习科目"
></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button @click='transmitClick(scope.row)'>传递</el-button>
</template>
</el-table-column>
</el-table>
<!-- 儿子组件 -->
<ChildView
:is-show="isOpen"
:row="row"
>
</ChildView>
</div>
</template>
<script>
import ChildView from './Child.vue'
export default {
components: {
ChildView },
data() {
return {
isOpen: false,
row: {
},
list: [
{
name: '王丽', study: 'Java' },
{
name: '李克', study: 'Python' }
]
}
},
methods: {
// 传递事件
transmitClick(row) {
this.isOpen = true;
this.row = row
}
}
}
</script>
v-bind="$attrs"
,这样孙子组件才能接收到数据<template>
<div class='child-view'>
<p>儿子组件</p>
<GrandChild v-bind="$attrs"></GrandChild>
</div>
</template>
<script>
import GrandChild from './GrandChild.vue'
export default {
// 继承所有父组件的内容
inheritAttrs: true,
components: {
GrandChild },
data() {
return {
}
}
}
</script>
<style lang="stylus">
.child-view {
margin: 20px
border: 2px solid red
padding: 20px
}
</style>
<template>
<div class='grand-child-view'>
<p>孙子组件</p>
<p>传给孙子组件的数据:{
{
row.name}} {
{
row.name !== undefined? '学习' : ''}} {
{
row.study}}</p>
</div>
</template>
<script>
export default {
// 不想继承所有父组件的内容,同时也不在组件根元素dom上显示属性
inheritAttrs: false,
// 在本组件中需要接收从父组件传递过来的数据,注意props里的参数名称不能改变,必须和父组件传递过来的是一样的
props: {
isShow: {
type: Boolean,
dedault: false
},
row: {
type: Object,
dedault: () => {
}
}
}
}
</script>
<style lang="stylus">
.grand-child-view {
border: 2px solid green
padding: 20px
margin: 20px
}
</style>
结果:
在上面提过,如果给子组件传递的数据,子组件不使用props接收,那么这些数据将作为子组件的特性,这些特性绑定在组件的HTML根元素上,在vue2.40版本之后,可以通过inheritAttrs = false
来控制这些特性是否显示在dom元素上 如:案例中父组件给子组件传递的row和isShow,子组件没有使用props接收,这个2个数据直接作为HTML的特殊属性。子组件使用inheritAttrs = true
,那么特性显示在dom上,如果设置为false,那么特性不显示在dom上
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180620.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有