组件通信,就是指组件与组件之间的数据传递
组件的数据是独立的,无法直接访问其他组件的数据
想用其他组件的数据 -> 组件通信
组件关系分类
1、父子关系
2、非父子关系
A包含B、C,BC没有包含关系,则A与B,A与C是父子关系,B与C是非父子关系。
父子关系组件通信解决方案:props 和 $emit
非父子关系组件通信解决方案:provide 和 inject 和 eventbus
通用解决方案:Vuex(适合复杂业场景)
父子通信
1、父组件通过props
将数据传递给子组件
父传子
<template>
<div id="app">
<MySon :titlee="myTitle"></MySon>
</div>
</template>
<script>
import MySon from './components/MySon.vue'
export default {
name: 'App',
components: {
MySon
},
data () {
return {
myTitle: '学前端了'
}
}
}
</script>
子用props接收
<template>
<div class="MySon">
我是son,我父亲的标题是: {{ title }}
</div>
</template>
<script>
export default {
props: ['title']
}
</script>
2、子组件利用$emit
通知父组件修改更新
子的$emit发射更新内容给父
<template>
<div class="MySon">
我是son,我父亲的标题是: {{ title }}
<button @click="handleClick">修改title</button>
</div>
</template>
<script>
export default {
props: ['title'],
methods: {
handleClick () {
this.$emit('changeTitle', '哈哈教育')
}
},
}
</script>
父监听子,并修改传来的新值
<template>
<div id="app"> <!-- 这里是监听 -->
<MySon :title="myTitle" @changeTitle="changeFn"></MySon>
</div>
</template>
<script>
import MySon from './components/MySon.vue'
export default {
name: 'App',
components: {
MySon
},
data () {
return {
myTitle: '学前端了'
}
},
methods: {
changeFn (newTitle) {
this.myTitle = newTitle
}
}
}
</script>