如何从 Vue 中的插件添加全局函数,如创建、方法、挂载?

Vic*_*rma 5 javascript vue.js vuejs2

在某些情况下,我不想mixins在我的插件中使用。我正在尝试添加一个自定义方法,例如created(), mounted(), methods{},以便在加载组件并运行我的自定义方法时可以访问其属性。示例:“自定义方法”

// @root/home.vue

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

Shi*_*ngh 2

.vue 文件

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

插件/customMethods.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
Run Code Online (Sandbox Code Playgroud)

main.js

import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)
Run Code Online (Sandbox Code Playgroud)

其作用是扩展所有 Vue 实例的默认选项,以便该行为应用于创建的每个 Vue 实例。然而,目前这还没有记录。

或者,这也可以通过在插件中使用全局 mixin 来实现。(根据您的用例,由于某种原因您不希望这样做。)

此外,一种高级用例是,在 期间合并自定义选项值时,我们可能需要特殊处理Vue.extend。例如,created钩子有一个特殊的合并策略,可以将多个钩子函数合并到一个数组中,以便所有的钩子函数都被调用。默认策略是简单覆盖。如果您需要自定义合并策略,您需要在以下位置注册Vue.config.optionMergeStrategies

Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
  // return merged value.
}
Run Code Online (Sandbox Code Playgroud)