1.傳遞屬性$attrs
說明:
a
t
t
r
s
只
代
表
的
是
那
些
沒
有
被
聲
明
為
p
r
o
p
s
的
屬
性
,
如
果
某
個
p
r
o
p
被
子
組
件
中
聲
明
了
(
就
是
這
個
屬
性
已
經
在
子
組
件
的
p
r
o
p
s
中
了
)
,
在
子
組
件
中
的
attrs只代表的是那些沒有被宣告為props的屬性, 如果某個prop被子組件中宣告了(就是這個屬性已經在子組件的props中了), 在子組件中的
attrs只代表的是那些沒有被聲明為props的屬性,如果某個prop被子組件中聲明了(就是這個屬性已經在子組件的props中了),在子組件中的attrs就會把宣告的prop剔除,
2.傳遞方法
l
i
s
t
e
n
e
r
s
包
含
了
父
作
用
域
中
的
(
不
含
.
n
a
t
i
v
e
修
飾
器
的
)
v
?
o
n
事
件
監
聽
器
,
它
可
以
通
過
v
?
o
n
=
"
listeners包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監聽器, 它可以通過 v-on="
listeners包含了父作用域中的(不含.native修飾器的)v?on事件監聽器,它可以通過v?on="listeners" 傳入內部組件——在創建更高層次的組件時非常有用,
三個組件:分別是:
parent.vue
son.vue
grandson.vue
// 父組件
<template lang="">
<div>
父組件
<Son :name="name" @change='change'></Son>
</div>
</template>
<script>
import Son from './son.vue'
export default {
data(){
return{
name:"周冬雨"
}
},
components:{
Son
},
methods: {
change(){
this.name = "馬冬梅";
}
},
}
//兒子組件
<template >
<div>
兒子組件
<GrandSon v-bind='$attrs'></GrandSon>//通過v-bin進行傳遞
</div>
</template>
<script>
import GrandSon from './grandson'
export default {
components:{
GrandSon
}
}
</script>
</script>
//孫子組件
<template >
<div>
孫子組件
姓名:{{$attrs.name}}
<button @click='handleClick'>改變</button>
</div>
</template>
<script>
export default {
methods: {
handleClick(){
this.$listeners.change();
}
},
}
</script>
頁面顯示:
1.最終在孫子組件中獲取到了他爺爺的值

2.通過$listeners孫子組件也可以獲取到他爺爺的方法,點擊按鈕效果如下,直接呼叫了爺爺的change方法,修改了name的值,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/305224.html
標籤:其他
上一篇:從零搭建TypeScript+Webpack環境(手把手記錄)
下一篇:轉前端的第一天
