问题
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