Post

[Vue] mixin | Component recycling

[Vue] mixin | Component recycling

mixin

믹스인은 여러 컴포넌트 간에 공통으로 사용하고 있는 로직, 기능들을 재사용하는 방법입니다. 믹스인에 정의할 수 있는 재사용 로직은 data, methods, create 등과 같은 컴포넌트 옵션입니다.

믹스인 코드 형식

믹스인을 주입 할 컴포넌트에 mixins 속성을 선언하고 배열 [] 안에 주입할 믹스인들을 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import EventBus from '@/utils/EventBus';

// mixin
export default {
  // 재사용할 component option & logic | data, methdos, create 등...
  created() {
    EventBus.$emit('start:spinner');
    this.$store
      .dispatch('FETCH_LIST', this.$route.name)
      .then(() => {
        EventBus.$emit('end:spinner');
      })
      .catch((e) => console.log(e));
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
  <div>
    <list-item></list-item>
  </div>
</template>

<script>
import ListItem from '../components/ListItem.vue';
import ListMixin from '../mixins/ListMixin'

export default {
  components: {
    ListItem,
  },
  mixins: [ListMixin],
}
</script>

NewsView.vue 컴포넌트에서 ListMixin.js에 선언 한 created() Life cycle Hook이 실행 됩니다.



참고
This post is licensed under CC BY 4.0 by the author.