props / $emit
父组件
<template>
<div class="home">
<HelloWorld msg="Welcome to Your Vue.js App" @showMsg="showMsg"/>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld,
},
methods: {
showMsg(msg) {
console.log(msg)
}
},
}
</script>
子组件
<template>
<h1 @click="clickHandler">{
{ msg }}</h1>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
emits: ['showMsg'], // Vue3
data() {
return {
name: 'hello-world'
}
},
methods: {
clickHandler() {
this.$emit('showMsg', 'hello world')
}
},
}
</script>