Vue - 重用方法的最佳方式

时间:2017-03-10 16:42:49

标签: vue.js vuejs2 vue-component

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

不是在每个组件中编写它们,而是将它们设为全局的最佳方法是什么?

2 个答案:

答案 0 :(得分:22)

密新

您可以为其创建mixin

  

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

如果您不想在所有组件中手动混合,可以使用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)

现在这些方法随处可见。您可以看到此here的示例。

答案 1 :(得分:8)

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