组件件通讯如下图:
父-->子
父组件传递数据通过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>
子-->父
- 子组件改变父组件传递的props(你会发现通过props中的Object类型参数传输数据,可以通过子组件改变数据内容。这种方式是可行的,但是不推荐使用,因为官方定义prop是单向绑定)
- 通过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>
连个组件之间进行通信
<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 //使用一个空的vue实例来作为事件总线
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>
注意一点
- 在vue的组件中,mounted()函数中的this指向。在组件中,this指向组件,但是在函数中的this却指向了root Vue