๋ฏน์ค์ธ์ ์ด๋ฆ์ด ๋ํ๋ด๊ณ ์๋ ๊ฒ์ฒ๋ผ ์ปดํฌ๋ํธ์ ๋ฌด์ธ๊ฐ๋ฅผ ์์ด ์ํ๋ ๊ฒ์ ๊ตฌํํ๋ ๊ธฐ๋ฅ์ด๋ค.
๋ฏน์ค์ธ์ ๊ตฌํํ๊ณ ๋์์ํค๋ ๊ณผ์ ์ ์์๋๋ก ์ฐ๋ฉด ์๋์ ๊ฐ์ด ์ ๋ฆฌํ ์ ์๋ค.
1. ๋ฏน์ค์ธํ ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ
2. ์ปดํฌ๋ํธ์ ๊ฐ์ฒด๋ฅผ ๋ฏน์ค์ธํ๊ณ
3. ๋๋จธ์ง ๋ถ๋ถ์ ๊ตฌํํด ์์ฑํ๋ค

์ฐธ๊ณ ํ ์ฌ์ดํธ
kr.vuejs.org/v2/guide/mixins.html
velog.io/@bluestragglr/Vue.js-Mixin
1. ๊ธฐ์ด
- Mixins๋ Vue ์ปดํฌ๋ํธ์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ๊ธฐ๋ฅ์ ๋ฐฐํฌํ๋ ์ ์ฐํ ๋ฐฉ๋ฒ์ด๋ค.
- mixin ๊ฐ์ฒด๋ ๋ชจ๋ ๊ตฌ์ฑ ์์ ์ต์ ์ ํฌํจํ ์ ์๋ค.
- ์ปดํฌ๋ํธ์ mixin์ ์ฌ์ฉํ๋ฉด ํด๋น mixin์ ๋ชจ๋ ์ต์ ์ด ์ปดํฌ๋ํธ์ ๊ณ ์ ์ต์ ์ โํผํฉโ๋๋ค.
// mixin ๊ฐ์ฒด ์์ฑ
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// mixin์ ์ฌ์ฉํ ์ปดํฌ๋ํธ ์ ์
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
2. ์ต์ ๋ณํฉ
- ๋ฏน์ค์ธ์์ ์ ์ธํ ์์ฑ์ ์ปดํฌ๋ํธ์์ ๋ค์ ์ ์ธํ ์ ์์ผ๋ฉฐ, ์ด ๊ฒฝ์ฐ ์ปดํฌ๋ํธ์ ์ ์ธ๋ ๊ฐ์ ์ฐ์ ํ์ฌ ๋ณํฉ๋๋ค.
- ์๋ฅผ ๋ค์ด 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" }
}
})
๊ฐ์ ์ด๋ฆ์ ํ ํจ์๊ฐ ๋ฐฐ์ด์ ๋ณํฉ๋์ด ๋ชจ๋ ํจ์๊ฐ ํธ์ถ๋์ง๋ง, mixin ํ ์ ์ปดํฌ๋ํธ ์์ฒด์ ํ ์ด์ ์ ํธ์ถ๋๋ค.
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"
3. ์ ์ญ Mixin
mixin์ ์ ์ญ์ผ๋ก ์ ์ฉํ ์๋ ์์ง๋ง, mixin์ ์ ์ญ์ผ๋ก ์ ์ฉํ๋ฉด ์ดํ์ ์์ฑ๋ ๋ชจ๋ Vue ์ธ์คํด์ค์ ์ํฅ์ ๋ฏธ์น๋ฏ๋ก ์ฃผ์ํด์ผ ํ๋ค.
// `myOption` ์ฌ์ฉ์ ์ ์ ์ต์
์ ์ํ ํธ๋ค๋ฌ ์ฃผ์
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"
'๐ปWEB FrontEnd > ํ๋ ์์ํฌ Vue' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ฌ์ฌ์ฉ & ์ปดํฌ์ง์ (2) - ์ฌ์ฉ์ ์ง์ ๋๋ ํฐ๋ธ (0) | 2021.02.26 |
---|---|
์ธ๋ผ์ธ ์คํ์ผ ๋ฐ์ธ๋ฉ (0) | 2021.02.25 |
ํด๋์ค ๋ฐ์ธ๋ฉ (0) | 2021.02.25 |
v-model ๋ฐ์ธ๋ฉ (0) | 2021.02.25 |
CSR์ SSR์ ์ฅ๋จ์ (0) | 2021.02.08 |