Vue Mixins

YEZI🎐·2022년 12월 6일
1

Vue

목록 보기
25/45

Mixins

Basics

Mixins는 Vue 컴포넌트에서 재사용 가능한 기능을 배포하는 유연한 방법이라고 소개한다.

  • 믹스인(Mixin) : 다중 상속을 지원하는, 구현된 인터페이스를 의미함

의미 그대로, 컴포넌트에 원하는 기능을 실행하는 객체(컴포넌트와 유사)를 커스텀한 뒤 이를 혼합하는 기법이다.
(Mixin을 제대로 활용하려면, 컴포넌트 Lifecycle에 대한 이해가 어느정도 동반되어야 한다.)

// 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!"

옵션 병합

Data 값 병합

기본적인 data, computed 등의 속성들을 Mixin 으로 병합할 수 있다.
단, 객체가 중첩되면 컴포넌트에서 선언한 값으로 재귀하여 병합된다.

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)
    // output : { message: "goodbye", foo: "abc", bar: "def" }
  }
})

Lifecycle 함수(메서드) 병합

같은 Lifecycle 에서 Hooks(함수)를 호출할 경우,
Mixin의 Hooks가 컴포넌트의 Hooks 보다 먼저 호출된다.

var mixin = {
  created: function () {
    console.log('mixin hook called')
  }
}

new Vue({
  mixins: [mixin],
  created: function () {
    console.log('component hook called')
  }
})

// output : "mixin hook called"
// output : "component hook called"

객체 값 병합 : methods, components, directives

위 프로퍼티들과 같이 객체 값을 요구하는 옵션은 같은 객체에 병합된다.
여기서 충돌하는 키가 존재하면, 컴포넌트의 프로퍼티가 우선순위를 갖는다.

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을 전역에서도 활용할 수 있다.
이를 적절히 활용하면 사용자 정의 옵션에 대한 처리 로직을 주입할 수 있다.

// `myOption` 사용자 정의 옵션을 위한 핸들러 주입
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
// output : "hello!"

단, Mixin을 전역으로 걸면 이후에 생성된 모든 전역 인스턴스에 영향을 미치므로 지양되는 패턴이다.

사용자 정의 옵션 병합 전략

Vue.config.mixin에 함수를 만들고, 이를 통해 추가되는 객체(methods 등)에 값을 추가하는 병합 전략을 소개한다.

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
  // return 병합된 값
}

객체 기반 옵션에서 간단하게 사용할 수 있다.

var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods


References

profile
까먹지마도토도토잠보🐘

1개의 댓글

comment-user-thumbnail
2022년 12월 6일

mixin 개념에 대해 알아가서 매우 좋습니다.
좋은 글이 참 많네요. 화이팅하세요 ^^

답글 달기