수색…


글로벌 믹스 인

믹스 인을 전 세계적으로 적용 할 수도 있습니다. 주의하십시오! mixin을 전역 적으로 적용하면 이후에 생성되는 모든 Vue 인스턴스에 영향을 미칩니다. 적절히 사용하면 사용자 정의 옵션에 대한 처리 논리를 삽입하는 데 사용할 수 있습니다.

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

글로벌 믹스는 제 3 자 구성 요소를 포함하여 생성 된 모든 단일 Vue 인스턴스에 영향을 미치기 때문에 희박하고 신중하게 사용하십시오. 대부분의 경우, 위 예제에서와 같이 사용자 지정 옵션 처리에만 사용해야합니다.

사용자 지정 옵션 병합 전략

사용자 지정 옵션을 병합하면 기존 전략을 사용하여 기존 값을 덮어 씁니다. 사용자 지정 논리를 사용하여 사용자 지정 옵션을 병합하려면 Vue.config.optionMergeStrategies 함수를 연결해야합니다.

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
  // return mergedVal
}

대부분의 객체 기반 옵션의 경우 methods 사용하는 것과 동일한 전략을 간단하게 사용할 수 있습니다.

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

기초

Mixins는 Vue 구성 요소에 재사용 가능한 기능을 배포하는 유연한 방법입니다. mixin 객체는 모든 구성 요소 옵션을 포함 할 수 있습니다. 구성 요소가 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과 구성 요소 자체에 중복 옵션이 포함되어 있으면 적절한 전략을 사용하여 "병합"됩니다. 예를 들어, 같은 이름의 훅 함수는 모두 배열로 병합되므로 모두 호출됩니다. 또한 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"

methods , componentsdirectives 과 같은 객체 값을 필요로하는 옵션은 동일한 객체에 병합됩니다. 이러한 객체에 충돌하는 키가있을 경우 구성 요소의 옵션이 우선 순위를 갖습니다.

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"

동일한 병합 전략이 Vue.extend() 에서 사용된다는 점에 유의하십시오.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow