한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online를 들으며 정리한 내용입니다.
Vue.js 가이드문서에서 더 자세한 내용을 확인할 수 있습니다.
App.vue
<template>
<MyBtn
class="heropy"
style="color: red;"
color="#ff0000" //red의 16진수 코드
@hello="log">
Apple
</mybtn>
</template>
<script>
import MyBtn from '~/components/MyBtn'
export default {
components: {
MyBtn
},
methods: {
log() {
console.log('Hello world!')
}
}
}
</script>
MyBtn.vue
<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>
MyBtn.vue
<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') //this대신 context사용 $는 제거
}
onMounted(() => {
console.log(props.color) //this대신 props사용
console.log(context.attrs) //this 대신 context사용 $는제거
})
return {
hello
}
}
}
</script>