组件间通信 | 青训营笔记

129 阅读3分钟

这是我参与【第四届青训营】笔记创作活动的第5天。

组件间通信基本原则

  1. 不要在子组件中直接修改父组件的状态数据
  2. 数据在哪,更新数据的行为(函数)就应该定义在哪

Vue组件间的通信方式

  1. props
  2. Vue的自定义事件
  3. 消息订阅与发布(如:pubsub库)
  4. slot
  5. vuex

1、props

1.1、使用组件标签传递数据时

<my-component name='tom' :age='3' :set-name='setName'></my-component>

1.2、定义MyComponent接收数据时

  1. 在组件内声明所有的props

  2. 声明方式:
    (1)只接收
    props: ['name', 'age', 'setName']
    (2)限制类型
    props: { name: String, age: Number, setNmae: Function }
    (3)限制类型、限制必要性、指定默认值
    props: { name: {type: String, required: true, default:xxx}, }

1.3、注意

  1. 此方式用于父组件向子组件传递数据
  2. 所有标签属性都会成为组件对象的属性, 模板页面可以直接引用
  3. 问题:
    a. 如果需要向非子后代传递数据必须多层逐层传递
    b. 兄弟组件间也不能直接props 通信, 必须借助父组件才可以

2、组件自定义事件

2.1、绑定事件监听语法

// 方式一: 通过v-on 绑定 
<Student @at="getStudentName"/> 

// 方式二: 通过$on() 
this.$refs.xxx.$on('at', this.getStudentName)

2.2、触发事件语法

// 触发事件(只能在父组件中接收) 
this.$emit(eventName, data)

2.3、示例

<!--通过父组件给子组件传递函数类型的props实现:子给父传递数据--> 
<School :getSchoolName="getschoolName" /> 

<!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) --> 
<Student @atguigu="getstudentName"/> 

<!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) --> 
<!-- <Student ref="student"/> -->

ref方法绑定事件:

mounted(){ this.$refs.student.$on( 'atguigu',this.getStudentName)//绑定自定义事件 
//this.$refs.student.$once( 'atguigu ',this.getStudentName)//绑定自定义事件(一次性,

子组件触发事件:

this.getSchoolName(this.name); // props方式

this.$emit('atguigu', this.name) //自定义事件方式

2.4、解绑事件:

this.$off('atguigu') //解绑一个自定义事件 
this.$off(['atguigu','demo']) //解绑多个自定义事件 
this.$off() //解绑所有自定义事件

注意:

  1. 此方式只用于子组件向父组件发送消息(数据)
  2. 问题: 隔代组件或兄弟组件间通信此种方式不合适

2.5、总结

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A 是父组件,B 是子组件,B 想给 A 传数据,那么就要在 A 中给 B 绑定自定义事件(事件的回调在 A 中)。

  3. 绑定自定义事件:
    第一种方式:
    在父组件中: <Demo @atguigu="test"/> 或 <Demo v-on:atguigu="test"/>
    第二种方式:
    在父组件中:

<Demo ref="demo"/> ...... mounted(){
    this.$refs.xxx.$on('atguigu',this.test) 
}
  1. 若想让自定义事件只能触发一次,可以使用 once 修饰符,或 $once 方法。
  2. 触发自定义事件:this.$emit('atguigu',数据)
  3. 解绑自定义事件:this.$off('atguigu')
  4. 组件上也可以绑定原生 DOM 事件,需要使用 native 修饰符。

注意:通过 this.refs.xxx.refs.xxx.on('atguigu',回调) 绑定自定义事件时,回调要么配置在 methods 中,要么用箭头函数,否则 this 指向会出问题!

3、全局事件总线(GlobalEventBus)

3.1、定义

一种组件间通信的方式,适用于任意组件间通信。

3.2、安装全局事件总线

new Vue({ 
    ......
    beforeCreate() {
        Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, 
    ...... 
})

3.3、使用事件总线

(1)接收数据: A组件想接收数据,则在 A 组件中给 $bus 绑定自定义事件,事件的回调留在 A 组件自身。

methods(){ 
    demo(data){......} 
} 
...... 
mounted() { 
    this.$bus.$on('xxxx',this.demo) 
}

(2)提供数据:在 B 组件中使用 $emit 触发 A 组件的回调函数

this.$bus.$emit('xxxx',数据)

注意:最好在 beforeDestroy 钩子中,用 $off 去解绑当前组件所用到的事件。

举例:

//引入Vue 
import Vue from 'vue' 
//引入App import App from './App.vue' 
//关闭Vue的生产提示 
Vue.config.productionTip = false 
//创建vm new Vue({ 
    el:'#app', 
    render: h => h(App), 
    beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线 }, 
})
<template> 
    <div class="student"> 
        <h2>学生姓名:{{name}}</h2> 
        <h2>学生性别:{{sex}}</h2> 
        <button @click="sendStudentName">把学生名给School组件</button>
    </div> 
</template> 

<script> 
    export default { 
        name:'Student', 
        data() { return { name:'张三', sex:'男', } }, 
        mounted() { // console.log('Student',this.x) }, 
        methods: { sendStudentName(){ this.$bus.$emit('hello',this.name) }}, 
    } 
</script> 

<style lang="less" scoped> 
    .student{ background-color: pink; padding: 5px; margin-top: 30px; } 
</style>
<template> 
    <div class="school"> 
        <h2>学校名称:{{name}}</h2> 
        <h2>学校地址:{{address}}</h2> 
    </div> 
</template> 

<script> 
    export default { 
        name:'School', 
        data() { return { name:'尚硅谷', address:'北京', } }, 
        mounted() { 
            // console.log('School',this) 
            this.$bus.$on('hello',(data)=>{ 
                console.log('我是School组件,收到了数据',data) 
            })
        }, 
        beforeDestroy() { 
            this.$bus.$off('hello') 
        }, 
    } 
</script> 

<style scoped> 
    .school{ background-color: skyblue; padding: 5px; } 
</style>

4、消息订阅与发布(pubsub)

4.1、定义

一种组件间通信的方式,适用于任意组件间通信。

4.2、使用步骤

  1. 安装 pubsub:npm i pubsub-js
  2. 引入: import pubsub from 'pubsub-js'
  3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
methods(){ 
    demo(data){......} 
} 
...... 
mounted() { 
    this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 
}
  1. 提供数据:pubsub.publish('xxx',数据)
  2. 最好在 beforeDestroy 钩子中,用 PubSub.unsubscribe(pid) 去取消订阅

注意:在 public 的自带 function 的回调函数中,this 是 undefined。

举例:

订阅消息

 mounted() {     
     // 订阅消息     
     this.pubId1 = pubsub.subscribe("checkItem", (msgName, data) => {
         this.checkItem(data);
     });     
     this.pubId2 = pubsub.subscribe("deleteItem", (msgName, data) => { 
         this.deleteItem(data); 
     });   
 },

发布消息

methods: { 
    // 获取需要修改勾选状态的数据的id    
    // 并将id向数据所在的App父组件传递     
    changeCheck(id) {       
        // 订阅消息       
        pubsub.publish("checkItem", id);     
    }, 
}

取消信息订阅

beforeDestroy() {    
    // 取消信息订阅    
    pubsub.unsubscribe(this.pubId1);    
    pubsub.unsubscribe(this.pubId2);   
},

image.png

5、自定义事件与原生事件

image.png

6、v-model实现父子组件通信

v-model 是组件通信方式的一种,v-model 是 Vue 框架中的指令,它主要结合表单元素一起使用(文本框、复选框、单选框等等),它主要的作用是收集表单数据。

v-model 实现原理:value 与 input 事件实现的,而且还需要注意可以通过 v-model 实现父子组件数据的同步。

image.png

image.png

7、属性修饰符sync

也是组件通信方式的一种,可以实现父子组件数据同步。

:money.sync,代表父组件给字符串传递 props[money],给当前子组件绑定一个自定义事件(update:money)

示例:

image.png

image.png

image.png

8、listenerslisteners与attrs

也是组件通信方式的一种,两者是组件实例的属性,可以获取到父组件给子组件传递props与自定义事件。

示例:封装一个 el-button 组件

image.png

image.png

9、childrenchildren与parent

ref 可以获取到某一个组件,子组件。

$children 组件实例的属性,可以获取到当前组件的全部子组件(数组)。

$parent 组件实例的属性,可以获取到当前子组件的父组件,进而可以操作父组件的数据与方法。

示例:

父组件:

image.png

image.png

image.png

10、混入 mixin

如果项目当中出现很多结构类似的功能,一般是使用组件复用。

如果项目当中很多组件的 JS 业务逻辑相似,可以使用 mixin。

image.png

image.png

11、插槽

image.png

image.png

image.png