Vue组件通信方式(一)

  组件与组件的关系,通常有父子关系,兄弟关系以及隔代关系。

  针对不同的场景,如何选用适合的通信方式呢?

(一) props/$emit

   parentComponent ==> childComponent

          child 通过 props [childParams] 接受父组件 parent 传递的过来的参数A;

      parent  通过 v-bind:childParams = parentParams 这种方式传递给 child。

   childComponent ==> parentComponent

      child    使用  this.$emit(eventChild,参数) 触发事件

          parent  通过 v-on:eventChild = methodParent  监听事件,获取参数

    代码如下:

     parentComponent:

<template>
    <div>
        <child v-bind:childAnimals="parentAnimals" v-on:titleChanged="updateChange"></child>
        <h2 v-text="title"></h2>
    </div>
</template>
<script>
import Child from './child'
export default {
    data() {
        return {
            title:'未改变时候的值',
            parentAnimals: ['dog','cat','pink']
        }
    },
    components: {
        'child':Child
    },
    methods: {
        updateChange(e) {
            const { name } = e;
            this.title = name;
        }
    }
}
</script>

      childComponent

<template>
    <div>
        <!--父组件传递过来的参数-->
        <ul>
            <li v-for="animal in childAnimals" v-bind:key="animal" v-text="animal"></li>
        </ul>

        <!--向父组件传递参数-->
        <button @click="changeParentTitle">改变父组件title</button>
    </div>
</template>
<script>
export default {
    data() {
        return {  }
    },
    // props:{
    //     animals:{
    //         type:Array,
    //         required:true
    //     }
    // }
    props:['childAnimals'],
    methods: {
        changeParentTitle() {
            this.$emit('titleChanged',{
                name: '子组件改变了父亲的title'
            });
        }
    }
}
</script>

(二) $emit /  $on

   通过一个全新 Vue 实例,作为中央事件处理中心,触发事件,监听事件。

   使用方法:

    触发事件: eventInstance.$emit(事件名A, params)
    监听事件: eventInstance.$on(事件名A,(params)=> { } )

    eventService.js

import Vue from 'vue';
export let eventInstance = new Vue();

  child.vue

<template>
    <div>
         <button @click="send">child发送消息</button>
    </div>
</template>
<script>
import { eventInstance } from '../commonEvent/eventService';
export default {
    data() {
        return {}
    },
    methods: {
        send() {
            eventInstance.$emit('msg-child',`this from child ${new Date().toLocaleString()}`);
        }
    }
}
</script>

   dog.vue 组件接受 child.vue 发送过来的信息

<script>
import { eventInstance } from '../commonEvent/eventService';
export default {
    data() { 
        return {}
    },
    components: {  },
    mounted() {
        eventInstance.$on('msg-child',(res)=>{
            console.log(res);
        });
    }
}
</script>

    

      

猜你喜欢

转载自www.cnblogs.com/xianrongbin/p/11691988.html