父->子:
方法一:使用pros
- 首先在parent里定義 需要傳的數(shù)據(jù):
parent:
<template>
<div>
<h1>parent</h1>
<m-child :msg="'from parent msg'"></m-child>
</div>
</template>
<script>
import MChild from './Child'
export default {
components: {
MChild,
},
}
</script>
- 然后在子組件中定義props接收數(shù)據(jù)并顯示:
child:
<template>
<div>
<h1>child</h1>
<h4>{{msg}}</h4>
</div>
</template>
<script>
export default {
props:{
msg:{
type:String,
defult:''
}
}
}
</script>
image.png
子->父
在子組件中綁定方法,在方法中使用this.$emit傳送數(shù)據(jù)。在父組件中監(jiān)聽定義的事件
child:
<template>
<div>
<h1>child</h1>
<button @click="sendToParent">子傳父</button>
</div>
</template>
<script>
export default {
methods:{
sendToParent(){
//第一個參數(shù)是父組件要監(jiān)聽的名字 第二個是數(shù)據(jù)
this.$emit('msgFromChild','我是子組件傳過來的數(shù)據(jù)')
}
}
}
parent:
<template>
<div>
<h1>parent</h1>
<m-child @msgFromChild="msgFromChild"></m-child>
<h4>{{msg}}</h4>
</div>
</template>
<script>
import MChild from './Child'
export default {
components: {
MChild,
},
data(){
return{
msg:''
}
},
methods:{
msgFromChild(val){
this.msg = val
console.log(val);
}
}
}
</script>
image.png
父子組件的訪問方式
有時候我們需要父組件直接訪問子組件会宪,子組件直接訪問父組件,或者是子組件訪問根組件姑宽。
- 父組件訪問子組件:使用$children/refs
- 子組件訪問父組件:$parent
方法一:$children
直接在父組件中使用this.$children[0].子組件中的data
$parent :當前組件樹的根 Vue 實例。如果當前實例沒有父實例村视,此實例將會是其自己斧拍。既然可以獲取到組件的實例,那么就可以調(diào)用組件的屬性或是方法進行操作
parent:
mounted(){
console.log(this.$children[0].xx);
}
child:
data(){
return{
xx:'xx'
}
},
顯示:
image.png
同樣关摇,子組件也可直接使用$parent獲取父組件的data荒叶。注意:是可以獲取data里定義的數(shù)據(jù)或者方法。
方法二:使用$ref
- 如果ref用在子組件上拒垃,指向的是組件實例停撞,可以理解為對子組件的索引瓷蛙,通過$ref可能獲取到在子組件里定義的屬性和方法悼瓮。
- 如果ref在普通的 DOM 元素上使用,引用指向的就是 DOM 元素艰猬,通過$ref可能獲取到該DOM 的屬性集合横堡,輕松訪問到DOM元素,作用與JQ選擇器類似冠桃。
prop和$ref之間的區(qū)別:
- prop 著重于數(shù)據(jù)的傳遞命贴,它并不能調(diào)用子組件里的屬性和方法。像創(chuàng)建文章組件時食听,自定義標題和內(nèi)容這樣的使用場景胸蛛,最適合使用prop。
- $ref 著重于索引樱报,主要用來調(diào)用子組件里的屬性和方法葬项,其實并不擅長數(shù)據(jù)傳遞。而且ref用在dom元素的時候迹蛤,能使到選擇器的作用民珍,這個功能比作為索引更常有用到襟士。
<m-child @msgFromChild="msgFromChild" ref="message"></m-child>
組件間傳值
- eventBus
- $attrs/listeners
- vuex
事件總線
main.js
//創(chuàng)建一個全局的用于綁定事件監(jiān)聽和分發(fā)事件的對象:Global Event Bus(全局事件總線)
//將其掛載到Vue的原型對象上,所有的組件對象都可以使用
Vue.prototype.xxx = new Vue()
//所以一般寫成Vue.prototype.$globalEventBus = new Vue() 見名知意
優(yōu)化:少new一個Vue
Vue.config.productionTip = false
//創(chuàng)建一個全局的用于綁定事件監(jiān)聽和分發(fā)事件的對象:Global Event Bus(全局事件總線)
new Vue({
beforeCreate(){
Vue.prototype.xxx = this
},
router,
store,
render: h => h(App)
}).$mount('#app')
組件1:
<template>
<div>
<h1>child</h1>
<button v-for="item in info" :key="item" @click="btnClick(item)">{{item.name}}</button>
</div>
</template>
<script>
export default {
data(){
return{
info:[
{ id:'1',name:'熱門推薦'},
{ id:'2',name:'精選家電'},
{ id:'3',name:'當季新裝'},
],
}
},
methods:{
btnClick(item){
this.xxx.$emit('clgitem',item)
}
}
}
</script>
組件2:
//略
methods:{
xx(item){
console.log(item);
}
},
mounted(){
//通過xxx來綁定事件監(jiān)聽
this.xxx.$on('clgitem',this.xx)
}
這樣可以實現(xiàn)任意組件通信嚷量。注意:綁定事件監(jiān)聽和分發(fā)事件是同一個組件