Vue中父子组件通信

我们在使用 Vue 的过程中,父子组件通信几乎是一个必会的知识点,本文就来说一下 Vue 中的父子组件通信

props/$emit

父向子:组件 A 通过 props 的方式向子组件 B 传递;

子向父:在子组件 B 中用$emit, 父组件 A 中 v-on 的方式实现

this.\$emit('methodInParentComponent','value');

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//父组件
<template>
<div id="app">
<HelloWorld v-on:titleChanged="updateTitle"></HelloWorld>
<h2>{{ title }}</h2>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld';
export default {
name: 'App',
data() {
return {
title: '传递的是一个值',
};
},
methods: {
updateTitle(e) {
//声明这个函数
this.title = e;
},
},
components: {
HelloWorld: HelloWorld,
},
};
</script>

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<header>
<h1 @click="changeTitle">{{ title }}</h1>
</header>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
title: 'Vue.js Demo',
};
},
methods: {
changeTitle() {
this.$emit('titleChanged', '子向父组件传值'); //自定义事件 传递值“子向父组件传值”
},
},
};
</script>
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信