Mixins는 Vue 컴포넌트에 재사용 가능한 기능을 배포하는 유연한 방법입니다. mixin 객체는 모든 구성 요소 옵션을 포함할 수 있습니다. 컴포넌트에 mixin을 사용하면 해당 mixin의 모든 옵션이 컴포넌트의 고유 옵션에 “혼합”됩니다.
- vue 공식문서
count가 1씩 증가하는 method를 만들어보자.// ComponentA.vue
<template>
<button @click="incrementCount">Clicked {{ count }} times</button>
</template>
<script>
export default {
name: 'component-a',
data() {
return { count: 0 }
},
methods: {
incrementCount() {
this.count += 1
}
},
}
</script>
incrementCount()의 재사용성을 위해 별도의 믹스인 파일 counterMixin.js 을 만들어 보자. // counterMixin.js
const counterMixin = {
data() {
return { count: 0 }
},
methods: {
incrementCount() {
this.count += 1
}
}
}
export default counterMixin;
// ComponentA.vue
<template>
<button @click="incrementCount">Clicked {{ count }} times</button>
</template>
<script>
import counterMixin from './counterMixin'
export default {
name: 'component-a',
mixins: [counterMixin],
}
</script>
재사용성 예시
버튼에 @click @mouseover @mouseout 등 각종 이벤트에 incrementCount()(1씩 증가하는 함수)를 적용할 수 있다.
*이벤트명 참고
아래의 이벤트명을 v-on: 또는 @와 같이 사용하면 된다.
| Event | Description |
|---|---|
| click | 마우스를 클릭했을 때 실행 |
| dbclick | 마우스를 더블 클릭했을 때 실행 |
| mouseover | 마우스 포인터가 요소 위로 올라왔을때 실행 |
| mouseout | 마우스 포인터가 요소 밖으로 벗어났을때 실행 |
| mousedown | 마우스의 버튼을 눌렀을 때 실행 |
| mouseup | 마우스 버튼을 놓았을 때 실행 |
| keydown | 키보드의 키를 눌렀을때 실행 |
| keyup | 키보드의 키를 놓았을 때 실행 |
| keypress | 키보드의 키를 눌렀다가 놓았을 때 실행 |
| change | 요소가 변경될 때 실행 |
| submit | <form>이 제출될 때 실행 |
| reset | <form>이 재설정될 때 실행 |
| select | <select>의 값이 선택되었을 때 실행 |
| focus | 태그에 포커스가 있을 때 실행 |