owned this note
owned this note
Published
Linked with GitHub
---
tags: vue
---
# Vue2 - Mixins
컴포넌트가 mixin을 사용하면, mixin에 있는 모든 옵션이 컴포넌트 자체의 옵션과 합쳐지게 된다.
```javascript
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
```
## Option Merging
mixin과 컴포넌트가 같은 Option을 갖고 있으면, 같은 옵션에 정의된 것들을 합친다.
만약, **data객체에서 같은 이름으로 충돌이 발생하면, 컴포넌트의 data가 더 높은 우선순위를 갖는다.**
```javascript
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
message: 'goodbye',
bar: 'def'
}
},
created: function () {
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
```
### Merging Hook Function
같은 이름의 hook 함수는 배열로 머지되어 전체가 호출될 수 있게 한다.
**mixin의 hook이 컴포넌트의 hook보다 먼저 호출된다.**
```javascript
var mixin = {
created: function () {
console.log('mixin hook called')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('component hook called')
}
})
// => "mixin hook called"
// => "component hook called"
```
### Merging Object Values
**key가 충돌한다면, 컴포넌트의 옵션이 더 높은 우선순위를 갖게 된다.**
```javascript
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
```
## Global Mixin
mixin을 globally 사용할 수 있다. 이는 이후에 생성될 모든 vue instance에 영향을 주게 된다.
custom option으로 로직을 모든 컴포넌트에 주입할 수 있다.
그치만 플러그인을 사용하는게 더 좋다! global mixin은 매우 주의해서 사용하거나, 사용하지 말자.
```javascript
// inject a handler for `myOption` custom option
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"
```
## Mixin의 단점과 Vue3의 Composition API
- mixin은 충돌이 발생하기 쉽다.
- 각 mixin의 프로퍼티가 같은 컴포넌트에서 합쳐지게 되므로, 모든 다른 mixin에서 어떠한 프로퍼티 이름을 갖는지를 확인하여 이름이 충돌나지 않도록 해야 한다.
- 프로퍼티가 어디서 왔는지 모른다.
- 컴포넌트가 여러 Mixin을 사용한다면, mixin의 프로퍼티를 사용할 때, 해당 프로퍼티가 어느 mixin에서 왔는지가 분명하지 않다.
- 제한된 재사용성
- mixin으로 파라미터를 넘겨서 그 로직을 바꿀 수 없다. 로직의 유연성이 떨어지게 된다.
이러한 이슈를 극복하기 위해, Vue3에서 Composition API를 사용하였다.
## 출처
- [Mixins - vue2](https://vuejs.org/v2/guide/mixins.html)