Vue CLI 시작하기 - Mixin

chajanee·2020년 4월 19일
2

Vue CLI 시작하기

목록 보기
5/6

main.js

import '@babel/polyfill'
import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'

Vue.config.productionTip = false

export const eventBus = new Vue({
  methods: {
    userWasEdited(date) {
      this.$emit('userWasEdited', date)
    }
  }
})

new Vue({
  render: h => h(App)
}).$mount('#app')

User.vue

<template>
    <div class="blue lighten-3 pa-3">
        <h1>User 컴포넌트</h1>
        <p>이름: {{ name }}</p>
        <p>{{ getDateAndTime(createdAt) }}</p>
        {{ helloToMixin }}
        <hr>
        <v-layout row wrap>
            <v-flex xs12 sm6>
                <UserDetail :name="name" :address="address" :phone="phone" :hasDog="hasDog"></UserDetail>
            </v-flex>
            <v-flex xs12 sm6>
                <UserEdit :name="name" :address="address" :phone="phone" :hasDog="hasDog" @child="parents"></UserEdit>
            </v-flex>
        </v-layout>
    </div>
</template>

<script>
    import UserDetail from "./UserDetail.vue"
    import UserEdit from "./UserEdit.vue"
    import { dateFormat } from "../mixins/dateFormat"

    export default {
        components: {
            UserDetail,
            UserEdit
        },
        data() {
            return {
                name: '차차',
                address: 'Seoul',
                phone: '1234-5678',
                hasDog: true,
                createdAt: null,
            }
        },
        computed: {
            helloToMixin() {
                return this.mixinData + ' 하잇!'
            }
        },
        created() {
            console.log('유저컴포넌트')
            this.createdAt = new Date()
        },
        methods: {
            parents(user) {
                this.name = user.name
                this.address = user.address
                this.phone = user.phone
                this.hasDog = user.hasDog
                console.log('부모가 받았어!')
            },
            // getDateAndTime(date) {
            //     if (date !== null) {
            //         let hour = date.getHours()
            //         let minutes = date.getMinutes()
            //         let fullDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
            //         return `${fullDate} ${hour}:${minutes}`
            //     } else {
            //         return null
            //     }
            // }
        },
        mixins: [dateFormat]
    }
</script>

UserDetail.vue

<template>
    <div class="red lighten-3 pa-3">
        <h3>자세한 회원 정보를 확인합니다.</h3>
        <p>상세사항</p>
        <v-list dense>
            <v-list-tile>
                <v-list-tile-content>이름:</v-list-tile-content>
                <v-list-tile-content class="align-end">
                    {{ name }}
                </v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
                <v-list-tile-content>주소:</v-list-tile-content>
                <v-list-tile-content class="align-end">
                    {{ address }}
                </v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
                <v-list-tile-content>전화번호:</v-list-tile-content>
                <v-list-tile-content class="align-end">
                    {{ phone }}
                </v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
                <v-list-tile-content>반려견유무:</v-list-tile-content>
                <v-list-tile-content class="align-end">
                    {{ hasDogKr }}
                </v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
                <v-list-tile-content>수정일자:</v-list-tile-content>
                <v-list-tile-content class="align-end">
                    {{ getDateAndTime(editedDate) }}
                </v-list-tile-content>
            </v-list-tile>
        </v-list>
    </div>
</template>

<script>
    import { eventBus } from "../main"
    import { dateFormat } from "../mixins/dateFormat";

    export default {
        data() {
            return {
                editedDate: null
            }
        },
        props: ['name', 'address', 'phone', 'hasDog'],
        computed: {
            hasDogKr() {
                return this.hasDog === true ? '있다' : '없다'
            }
        },
        created() {
            console.log('유저 디테일 컴포넌트')
            eventBus.$on('userWasEdited', (date) => {
                this.editedDate = date
            })
        },
        methods: {
            // getDateAndTime(date) {
            //     if (date !== null) {
            //         let hour = date.getHours()
            //         let minutes = date.getMinutes()
            //         let fullDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
            //         return `${fullDate} ${hour}:${minutes}`
            //     } else {
            //         return null
            //     }
            // }
        },
        mixins: [dateFormat]
    }
</script>

dateFormat.js

export const dateFormat = {
    created () {
        console.log('믹스인')
    },
    data() {
        return {
            mixinData: '나는 믹스인!'
        }
    },
    methods: {
        getDateAndTime(date){
            if (date !== null) {
                let hour = date.getHours()
                let minutes = date.getMinutes()
                let fullDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
                return `${fullDate} ${hour}:${minutes}`
            } else {
                return null
            }
        }
    }
}

공통적으로 쓰이는 날짜부분 2군데를 굳이 일일이 함수를 계속 쓰지않고
따로 하나를 빼서 재사용한다.

이처럼 여러개의 컴포넌트가 공통된 로직을 갖고있다면
코드낭비나 재사용성의 낭비, 수정하기 귀찮음 등등
여러 문제를 대비해 mixin으로 따로 빼서 사용을 해주자.


Reference
맨땅에 개발하기 - Vue CLI 시작하기

profile
🔥생존을 위해 고군분투 중🔥#스타트업 #프론트엔드 #인턴 #개발자 #포메이커스 💝학습 내용을 정리합니다. 잘못된 부분이 있을 경우 피드백 부탁드립니다. 감사합니다!

0개의 댓글