首页 技术 正文
技术 2022年11月19日
0 收藏 759 点赞 2,762 浏览 1868 个字

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

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

(一) 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>

    

     

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294