컴포넌트가 mixin을 사용하면, mixin에 있는 모든 옵션이 컴포넌트 자체의 옵션과 합쳐지게 된다.
// 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!"
mixin과 컴포넌트가 같은 Option을 갖고 있으면, 같은 옵션에 정의된 것들을 합친다.
만약, data객체에서 같은 이름으로 충돌이 발생하면, 컴포넌트의 data가 더 높은 우선순위를 갖는다.
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" }
}
})
같은 이름의 hook 함수는 배열로 머지되어 전체가 호출될 수 있게 한다.
mixin의 hook이 컴포넌트의 hook보다 먼저 호출된다.
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"
key가 충돌한다면, 컴포넌트의 옵션이 더 높은 우선순위를 갖게 된다.
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"
mixin을 globally 사용할 수 있다. 이는 이후에 생성될 모든 vue instance에 영향을 주게 된다.
custom option으로 로직을 모든 컴포넌트에 주입할 수 있다.
그치만 플러그인을 사용하는게 더 좋다! global mixin은 매우 주의해서 사용하거나, 사용하지 말자.
// 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를 사용하였다.
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing