Nomi Su@Coding

Record all of the coding problem

0%

[Vue.js] 父子組件溝通 - $emit / $on

每次都記不起來要如何在子組件中呼叫父組件,這邊來做個備忘錄

父組件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div id="app">
<child v-on:childMethod="parentMethod"></child>
</div>
</template>

<script>
import Child from './components/Child';
export default {
name: 'App',
components: {
Child,
},
methods: {
parentMethod() {
console.log('Hello World');
},
},
};
</script>

子組件:

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<button @click="handleClick">Emit</button>
</template>

<script>
export default {
methods: {
handleClick() {
this.$emit('childMethod');
},
},
};
</script>