parent-component.vue
<template>
<div>
<child-component :parent-message="msg"
@print="val => printMessage(val)"></child-component>
</div>
</template>
<script>
import ChildComponent from './components/child-component'
export default {
name: 'parent-component',
components: { ChildComponent },
data () {
return {
msg: '안녕하세요.'
}
},
methods: {
printMessage (val) {
console.log(val)
}
}
}
</script>
child-component.vue
<template>
<div>
<button @click="sendEvent()">Print</button>
</div>
</template>
<script>
export default {
name: 'child-component',
props: {
parentMessage: {
type: String,
default: void 0
}
},
methods: {
sendEvent () {
this.$emit('print', this.parentMessage)
}
}
}
</script>
Component 공통화 고려없이 생성했을 때의 문제점들
✔ 코드 가독성 및 유지관리 효율성 저하
✔ 컴포넌트 구조의 복잡성 증가
✔ 독릭접인 컴포넌트로의 변이
Component 공통화 적용 안한 코드
parent-component.vue
<template>
<div>
<child-component :contents="[
{
label: $t('exam_code'),
name: 'code',
id: 'exam_id',
}]></child-component>
</div>
</template>
<script>
import ChildComponent from './components/child-component'
export default {
name: 'parent-component',
components: { ChildComponent },
data () {
...
},
methods: {
...
}
}
</script>
child-component.vue
<template>
<div>
<input
v-if="content.group"
:maxlength="content.maxLength"
...
></input>
<!-- 문제 발생 -->
<input
v-else-if="content.id === 'exam_id'"
:maxlength="9"
...
></input>
<input
v-else
:maxlength="content.maxLength"
...
></input>
</div>
</template>
<script>
export default {
name: 'child-component',
props: {
contents: {
type: Array,
required: true,
},
maxLength: {
type: Number,
required: false,
},
},
methods: {
sendEvent () {
this.$emit(...)
}
}
}
</script>
parent-component.vue
<template>
<div>
<child-component :contents="[
{
label: $t('exam_code'),
name: 'code',
maxLength: '9',
}]></child-component>
</div>
</template>
<script>
import ChildComponent from './components/child-component'
export default {
name: 'parent-component',
components: { ChildComponent },
data () {
...
},
methods: {
...
}
}
</script>
child-component.vue
<template>
<div>
<input
v-if="content.group"
:maxlength="content.maxLength"
...
></input>
<input
v-else
:maxlength="content.maxLength"
...
></input>
</div>
</template>
<script>
export default {
name: 'child-component',
props: {
contents: {
type: Array,
required: true,
},
maxLength: {
type: Number,
required: false,
},
},
methods: {
sendEvent () {
this.$emit(...)
}
}
}
</script>