组件是vue的强大功能之一,组件实例的作用域是相互独立的,意味着不同组件之间的数据无法相互进行直接的引用,所以组件间的通信是非常重要的。
一、props / $emit
1、父组件向子组件传值(props的用法)
2、子组件向父组件传递数据($emit的用法)
二、ref / $refs
三、eventBus事件总线($emit / $on)
1、创建事件中心管理组件之间的通信
2、发送事件 假设有两个兄弟组件firstCom和secondCom
3、接收事件
四、vuex数据共享
五、依赖注入(provide / inject)
六、$parent / $children
七、$attrs / $listeners
八、总结
一、props / $emit
父组件通过 props
向子组件传递数据,子组件通过 $emit
和父组件通信
1、父组件向子组件传值(props的用法)
props的特点:
- props只能是父组件向子组件进行传值,props使得父子组件之间形成一个单向的下行绑定。子组件的数据会随着父组件的更新而响应式更新。
- props可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以是传递一个函数。
- props属性名规则:若在props中使用驼峰形式,模板中标签需要使用短横线的形式来书写。
用法:
父组件:
// 父组件
<template>
<div id="father">
<son :msg="msgData" :fn="myFunction"></son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
name: father,
data() {
msgData: "父组件数据";
},
methods: {
myFunction() {
console.log("vue");
}
},
components: {
son
}
};
</script>
子组件:
// 子组件
<template>
<div id="son">
<p>{
{
msg}}</p>
<button @click="fn">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: ["msg", "fn"]
};
</script>
2、子组件向父组件传递数据($emit的用法)
$emit的特点:
$emit
绑定一个自定义事件,当这个事件被执行的时候就会将参数传递给父组件,而父组件通过v-on
监听并接收参数。
用法:
父组件:
// 父组件
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{
{
currentIndex}}</p>
</div>
</template>
<script>
import comArticle from './test/article.vue'
export default {
name: 'comArticle',
components: {
comArticle },
data() {
return {
currentIndex: -1,
articleList: ['红楼梦', '西游记', '三国演义']
}
},
metho