Vue.js

axios intercepter

axios intercepter를 이용하면 서버에 요청하기 바로전에 어떠한 로직을 추가할 수 있다. ex) 로그인시 받아온 토큰값을 실어주는 로직등… 반대로 서버에 응답을 받기전에 어떠한 로직을 추가할 수 있다.

Token 설정

항상 token 값은 header에 Autorization에 실어준다.

dynamic import

spa 특성상 초기 진입시 모든페이지를 로드하여 로딩이 느리다. dynamic import를 통하여 문제를 해결할 수 있다.

new VueRouter({
    path: '/login',
    component: () => import('./components/login.vue');
})

vue.js(외부 라이브러리) 플러그인 모듈화

import Chart from 'chart.js';

export default {
    install(Vue) {
        Vue.prototype.$_Chart = Chart;
    }
}

// main.js
import Vue from 'Vue';
import ChartPlugin from './plugin/ChartPlugin.js';

Vue.use(ChartPlugin);

어느 컴포넌트에서든지 this.$_Chart로 접근할 수 있다.

컴포넌트 디자인 패턴

Common - 기본적인 컴포넌트 등록과 컴포넌트 통신

일반적인 상위 컴포넌트에서 비즈니스 로직이있고 하위 컴포넌트는 props를 통해 데이터를 보여주고, 이벤트를 상위 컴포넌트에 올려주는 보여주기용 컴포넌트

slot - 마크업 확장이 가능한 컴포넌트

slot 이라는 vue디렉토리를 이용하여 상위 컴포넌트에서 하위 컴포넌트 템플릿을 제어하는 디자인 패턴

controlled - 결합력이 높은 컴포넌트

하위 컴포넌트에 input box value값을 상위 컴포넌트에서 제어하는 디자인 패턴

// app.vue
<template>
 <check-box v-model="checked">
</template>

<script>
import CheckBox './components/CheckBox.vue

export default {
    components: {
        CheckBox
    }
}
</script>

// CheckBox.vue
<template>
    <input type="checkbox":value="value" @click="checked">
</template>
<script>
export default {
    props: {
        value: Boolean
    },
    methods: {
        checked() {
            this.$emit('input', !this.value)
        }
    }
}
</script>

Renderless - 데이터 처리 컴포넌트

render function 사용법

new Vue({
    render(createElement) {
        return createElement('태그이름', '태그 속성', '하위 태그');
    }
})

this.$scopedSlots.default({}) 하위 컴포넌트에 데이터를 render함수를통해 상위에서 접근할 수 있게 해주는 메소드

// 하위 컴포넌트 FetchData.vue
new Vue({
    props: {
        url: String
    }
    created() {
        axios.get(this.url)
        .then((res) => {
            this.items = res.data;
            this.state = !this.state;
        })
    }
    data() {
        return {
            state: false,
            items: []
        }
    }
    render() {
        return this.$scopedSlots.default({
            state: this.state,
            items: this.items
        })
    }
})

// 상위 컴포넌트
<fetch-data url="domain.com">
    <div slot-scope="{ items, state }">
        <div v-if="!loading">
            
        </div>
        <div v-if="loading">
            Loading...
        </div>
    </div>
</fetch-dat>

$scopedSlots 라는 메소드를 이용해 데이터를 불러와서 뿌려주는 설계 방식을 이런식으로도 할 수 있다.

env 환경 변수 파일을 이용한 옵션 변경 방법

vue/cli 3버전 부터 가능 Root디렉토리에 .env라는 파일을 생성한뒤

// 변수 = 값
VUE_APP_변수이름 = HELLO

// app.vue
new Vue({
    created() {
        console.log(VUE_변수이름) // HELLO
    }
})

보통 이런 환경변수를 설정하기 위해서는 webpack에 definePlugin을 이용하여 설정하는데 .env파일에서도 설정할 수 있다.

.env 파일에 환경변수를 개발일 경우와, 운영일 경우 다를수 있어 .env.development, env.production으로 나눠서 작성할 수 있다. 빌드 모드(webpack)에 따라 접근하는 우선순위가 다르다.