The relationship between the components and assemblies, usually a parent-child relationship, brotherhood and inter-generational relationships.
For different scenarios, how to choose appropriate communication method?
(A) props / $ emit
parentComponent ==> childComponent
child by props [childParams] parent component passed over the parent accepts the parameter A;
parent by v-bind: childParams = parentParams transmitted in this way to the child.
childComponent ==> parentComponent
child using this $ emit (eventChild, parameters). triggering event ;
parent by v-on: eventChild = methodParent listen for events, acquisition parameters .
code show as below:
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> <- - parent component parameters passed to it!> <ul> <li V- for = "Animal in childAnimals" v-the bind: Key = "Animal" v-text = "Animal"> </ Li> </ UL> <-! pass parameters to the parent element -> <Button @ = the Click "changeParentTitle"> change parent component title </ Button> </ div> </ Template> <Script> Export default { Data () { return {} }, // The props: { // Animals: { // type: the Array, // required:true // } // } The props: [ 'childAnimals' ], Methods: { changeParentTitle () { the this $ EMIT ( 'the titleChanged'. , { name: 'father changed subassembly title' }); } } } </ Script>
(二) $ emit / $ is
Through a brand-new Vue example, as the central event processing center, trigger events, listen for events.
Instructions:
Triggering Event: EventInstance $ EMIT (event name A, params).
Listening to events: . EventInstance $ ON (event name A, (params) => { })
eventService.js
Import View from 'view' ; export let eventInstance = new View ();
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 component accepts information sent from child.vue
<script> import { eventInstance } from '../commonEvent/eventService'; export default { data() { return {} }, components: { }, mounted() { eventInstance.$on('msg-child',(res)=>{ console.log(res); }); } } </script>