vue组件的祖孙透传
我们知道vue可以通过vuex很好的处理各组件之间值状态,其实vue还有另外的方法也可以做到,它就是 v-bind=“$attrs”
parent 父组件
<template
>
<section
>
<son
:name
="name" :age
="age" :gender
="gender" :job
="job" @isClick
="isClick" @add
="add" @getGrandchildrenData
="getGrandchildrenData" />
<input type
="text" v
-model
="name">
<input type
="text" v
-model
="age">
<input type
="text" v
-model
="gender">
<input type
="text" v
-model
="job">
</section
>
</template
>
<script
>
import centers from
'./son';
export
default {
data
() {
return {
name
: '李四',
age
: '18',
gender
: '男',
job
: '程序员'
}
},
components
: {
son
},
methods
: {
add
() {
console
.log('parent 的 add 方法')
},
isClick
() {
console
.log('parent 的 isClick 方法')
},
getGrandchildrenData
(data
){
console
.log('孙子传来的数据',data
)
}
}
};
</script>
son 儿子组件
<template>
<section>
<div>
<grandchildrenv-bind="$attrs" v-on="$listeners" />
</div>
{{name}}
{{age}}
</section>
</template>
<script>
import grandchildren from './grandchildren';
export default {
components: {
grandchildren
},
props: {
name: {
type: String,
default: 'default'
},
age: {
type: String,
default: 'default'
}
}
};
</script>
孙子组件 grandchildren
<template
>
<section
>
<div
>
{{ $attrs['job'] }} 在
$attrs里面只会有props没有注册的属性
<br
>
<p
>bottom 性别
=> {{ gender
}}</p
>
<p
>bottom 工作
=> {{ $attrs['job'] }}</p
>
<button
@click
=“send”
>给爷爷数据
</button
>
</div
>
</section
>
</template
>
<script
>
export
default {
props
: {
gender
: {
type
: String
,
default: ''
}
},
methods
:{
send
(){
this
.$emit('getGrandchildrenData','来自孙子的祝福数据')
}
},
mounted
() {
console
.log(this
.$attrs);// { job:'程序员'} 非 props 外的属性
console
.log(this
.$listeners);// 爷爷给儿子的的方法
this
.$listeners.isClick
();//孙子组件 调用爷爷组件的方法 isClick
this
.$listeners.add
();//孙子组件 调用爷爷组件的方法 add
}
};
</script>
释义
在父组件 parent 中,传递了给儿子 son 组件两个方法 和 几个属性值,
再到儿子 son 组件中,儿子son组件 再通过 `v-bind="$attrs" v-on="$listeners"` 方式给孙子grandchildren组件 传递,当然是除了儿子son组件拿取了自己props的值剩下的属性,
再到 grandchildren 孙子组件里,$attrs 对象身上 只有 除了 props 外的属性,因为你是 porps 直接接收,没有被接收到的属性 就留在了 $attrs 身上,可以直接通过 $attrs[ key ] 的方式使用,也是响应式的
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
你好