Vue - 重用方法的最佳方式

Vue - best way to reuse methods

在 vue 2 中 - 重用 vue 方法的正确做法是什么?

与其将它们写在每个组件中,不如让它们成为全局的最佳方式是什么?

混音

你可以为它创建一个mixin

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

示例:

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

如果不想在所有组件中手动混合,可以使用global mixin

// inject a handler for `myOption` custom option
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

插件

创建全局可用方法的另一种方法是创建 plugin.

MyPlugin.install = function (Vue, options) {
  //  add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }
  //  inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })
  //  add an instance method
  Vue.prototype.$myMethod = function (options) {
    // something logic ...
  }
}

通过调用 Vue.use() 全局方法使用插件:

Vue.use(MyPlugin)

现在这些方法将随处可用。你可以看到这个 .

的例子

在 Vue2 中没有真正好的代码重用机制,它们只是变通办法,有时如果设计不当,它们会增加比它们提供的更多的麻烦。但幸运的是,Vue3 提供了 Vue 长期以来缺少的东西,新的 Composition API(真正的组合而不是合并逻辑(mixins)或包装逻辑(slots 或 scoped-slots)。即使它是 Vue 的一部分3,你仍然可以在你的 Vue2 应用程序中将它作为一个单独的模块使用。Composition API 提供与 Hooks 引入 React 社区时相同的快乐开发体验。