Vue - 重用方法的最佳方式

Qar*_*Qar 9 vue.js vue-component vuejs2

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

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

Sau*_*abh 23

混入

你可以为它创建一个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!"
Run Code Online (Sandbox Code Playgroud)

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

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

插入

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

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 ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Vue.use(MyPlugin)
Run Code Online (Sandbox Code Playgroud)

现在这些方法随处可见.你可以在这里看到一个例子.


Hum*_*mad 6

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