부모 컴포넌트
<template>
<MyBtn
class="heropy"
style="color: red;"
color="#ff0000"
@hello="logo">
Apple
</MyBtn>
</template>
<script>
import MyBtn from '~/components/MyBtn'
export default {
components: {
MyBtn
},
methods: {
log() {
console.log('Hello world')
}
}
}
</script>
자식 컴포넌트
<template>
<div
v-bind="$attrs"
class="btn"
@click="hello">
<slot></slot>
</div>
</template>
<script>
export default {
inheritAttrs: false,
props: {
color: {
type: String,
default: 'gray'
}
},
emits: ['hello'],
mounted() {
console.log(this.color)
console.log(this.$attrs)
},
methods: {
hello() {
this.$emit('hello')
}
}
}
</script>
자식 컴포넌트 : 컴포지션 API - props, context 사용
<template>
<div
v-bind="$attrs"
class="btn"
@click="hello">
<slot></slot>
</div>
</template>
<script>
import { onMounted } from 'vue'
export default {
inheritAttrs: false,
props: {
color: {
type: String,
default: 'gray'
}
},
emits: ['hello'],
setup(props, context) {
function hello() {
context.emit('hello')
}
onMounted(() => {
console.log(props.color)
console.log(context.attrs)
})
return {
hello
}
}
}
</script>