Vue - best way to reuse methods

风流意气都作罢 提交于 2019-12-08 16:10:03

问题


In vue 2 - what is correct practise for reusing vue methods?

Instead of writing them in each component, what is the best way to make them global?


回答1:


Mixin

You can create a mixin for it

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.

Example:

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

If you dont want to mix it manually in all components, you can use global mixin

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

Plugin

Another way to create a method available globally is to create a 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 ...
  }
}

Use plugins by calling the Vue.use() global method:

Vue.use(MyPlugin)

Now these methods will be available everywhere. You can see an example of this here.



来源:https://stackoverflow.com/questions/42723499/vue-best-way-to-reuse-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!