組件件通訊如下圖:

image.png
父-->子
父組件傳遞數(shù)據(jù)通過props
通過在子組件中定義props對象來定義屬性,用來保存父組件的變量
**父組件代碼**
<template>
<header-box :title-txt="showTitleTxt"></header-box>
</template>
<script>
import Header from './header'
export default {
name: 'index',
components: {
'header-box': Header
},
data () {
return {
showTitleTxt: '首頁'
}
}
}
</script>
**子組件代碼**
<template>
<header>
{{thisTitleTxt}}
</header>
</template>
<script>
export default {
name: 'header-box',
props: {
titleTxt: String
},
data () {
return {
thisTitleTxt: this.titleTxt
}
}
}
</script>

image.png
子-->父
- 子組件改變父組件傳遞的props(你會發(fā)現(xiàn)通過props中的Object類型參數(shù)傳輸數(shù)據(jù),可以通過子組件改變數(shù)據(jù)內(nèi)容。這種方式是可行的,但是不推薦使用,因?yàn)楣俜蕉xprop是單向綁定)
- 通過
emit
*通過$on,$emit*
**父組件代碼**
<template>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</template>
<script>
import ButtonCounter from './buttonCounter'
export default {
name: 'index',
components: {
'button-conuter': ButtonCounter
},
data () {
return {
total: 0
}
},
methods: {
incrementTotal () {
this.total++
}
}
}
</script>
**子組件代碼**
<template>
<button @click="incrementCounter">{{counter}}</button>
</template>
<script>
export default {
name: 'button-counter',
data () {
return {
counter: 0
}
},
metheds: {
incrementCounter () {
this.$emit('increment')
this.counter++
}
}
}
</script>

image.png
連個(gè)組件之間進(jìn)行通信
<script src="./node_modules/vue/dist/vue.js"></script>
<div id="app">
<people1></people1>
<people2></people2>
</div>
<script>
var bus = new Vue()
Vue.prototype.bus = bus //使用一個(gè)空的vue實(shí)例來作為事件總線
var people1 = {
data() {
return {
title: '吃飯飯'
}
},
methods: {
change() {
this.bus.$emit('tochange', '首頁')
}
},
template:`<div @click='change'>{{title}} </div>`
}
var people2 = {
mounted() {
let that = this
console.log(this)
console.log(that)
this.bus.$on('tochange', function (title) {
console.log(that)
console.log(this.txt)
that.txt = title
console.log(this.txt)
console.log(title)
})
},
methods:{
chengeto(){
this.data(this.title)
}
},
data(title) {
return {
txt:
'title'
}
},
template:`<div>{{txt}} </div>`,
}
var vm = new Vue({
el:'#app',
components:{
people1,
people2
}
})
</script>
注意一點(diǎn)
- 在vue的組件中,mounted()函數(shù)中的this指向。在組件中,this指向組件,但是在函數(shù)中的this卻指向了root Vue