programing

Vue에서 플러그인에서 생성, 메서드, 마운트 등의 글로벌 기능을 추가하는 방법

projobs 2023. 2. 3. 21:06
반응형

Vue에서 플러그인에서 생성, 메서드, 마운트 등의 글로벌 기능을 추가하는 방법

경우에 따라서는 사용하지 않을 수도 있습니다.mixins내 플러그인에서.다음과 같은 커스텀 메서드를 추가하려고 합니다.created(),mounted(),methods{}컴포넌트가 로드되었을 때 그 속성에 액세스하여 커스텀 메서드를 실행할 수 있습니다.예: "커스텀방법"

// @root/home.vue

<script>
export default {
  name: 'Home',
  props: {
    msg: String
  },
  mounted(){
    //
  },
  methods{
    //
  },
  customMethod{
    
  }
}
</script>

.vue 파일

<script>
export default {
 customMethod () { // Custom option.
  console.log('custom method executed!')
 },
 methods: {},
 created () {},
 mounted () {}
}
</script>

플러그인/커스텀Methods.js

const customMethods = {
  install (Vue) {
    // INSTALL
    if (this.installed) return
    this.installed = true

    Vue.options = Vue.util.mergeOptions(Vue.options, {
     created: function () {
      if (this.$options.customMethod) { // If found in the component.
       this.$options.customMethod() // Execute the customMethod.
      }
     }
    })
  }
}

export default customMethods

main.discloss.main.discloss.

import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)

이렇게 하면 모든 Vue 인스턴스에 대한 기본 옵션이 확장되어 생성된 모든 Vue 인스턴스에 동작이 적용됩니다.그러나 이것은 현재 문서화되어 있지 않다.

또는 플러그인에서 글로벌 믹스인을 사용하여 이를 수행할 수도 있습니다.(사용 사례에 따라서는 어떤 이유로든 원하지 않습니다.)

게다가 고도의 사용 사례의 하나로, 커스텀 옵션 값을 Marge 할 때 특별한 처리가 필요할 수 있습니다.Vue.extend예를 들어,created훅에는 여러 후크 함수를 하나의 배열로 병합하여 모든 후크 함수를 호출하는 특별한 병합 전략이 있습니다.기본 전략은 단순 덮어쓰기입니다.커스텀 머지 전략이 필요한 경우는, 다음의 URL 로 등록할 필요가 있습니다.Vue.config.optionMergeStrategies:

Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
  // return merged value.
}

모든 컴포넌트가 액세스 할 수 있습니다.customMethod주사하면Vue.prototype다음과 같습니다.

Vue.prototype.customMethod = function() {}

언급URL : https://stackoverflow.com/questions/59114128/how-to-add-global-funtions-like-create-methods-mounted-from-a-plugin-in-vue

반응형