1 minute read


1. Mixin 이란?

믹스인(Mixins)은 여러 컴포넌트 간에 공통으로 사용하고 있는 로직, 기능들을 재사용하는 기능이다.
믹스인에 정의할 수 있는 재사용 로직은 data, methods, created 등과 같은 컴포넌트 옵션이며 HTML이나 CSS는 믹스인 하지 않는다.


2. 기본 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// mixin 객체 정의
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// mixin 사용
var Component = Vue.extend({
  mixins: [myMixin]
})

// result : "hello from mixin!"
var component = new Component() 


3. 옵션 병합

mixin과 컴포넌트에 같은 이름으로 된 함수나 변수가 있다면 컴포넌트 자신의 값이 우선된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var mixin = {
  data: function () {
    return {
      message: 'Mixin',
    }
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: 'Component',
    }
  },
  created: function () {
    // result : { message: "Component" }
    console.log(this.$data);
  }
})

위와 같은 현상이 일어나는 이유는 라이프 사이클에서 확인해 볼 수 있다. mixin과 컴포넌트의 created 영역에 로그를 찍고 확인해 보면 mixin의 로그가 먼저 출력되고 이 후 컴포넌트의 로그가 출력되는 것을 볼 수 있다.
따라서 같은 이름의 함수나 변수가 mixin과 컴포넌트에 선언되어 있는 경우 컴포넌트 자신의 값으로 덮어씌어 지게되서 자신의 값으로 출력되는 것이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var mixin = {
  data: function () {
    return {
      message: 'Mixin',
    }
  },
  created: function(){
    console.log('Mixin Created');
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: 'Component',
    }
  },
  created: function () {
    console.log("Component Created");
  }
})

//result : 'Mixin Created'
//         'Component Created'


4. Mixin 전역 사용

Mixin은 공동으로 사용되는 로직들을 정리해 놓은 것으로 여기저기 불러다 쓸 일이 많다. 그럴때마다 import 해서 쓰기 번거로우니 전역으로 등록해서 사용하도록 하자.

1
2
3
4
5
//main.js
import Vue from 'vue';
import Mixin from './mixins/';    //mixin 파일 import

Vue.mixin(Mixin);

위와 같이 공동 사용되는 로직을 하나의 파일에 저장해두고 main.js에 선언해두면 사용중인 프로젝트 파일에서 this를 사용해서 불러올 수 있다.