你可以为它创建一个mixin
mixin是为Vue组件分发可重用功能的一种灵活方式.mixin对象可以包含任何组件选项.当组件使用mixin时,mixin中的所有选项都将"混合"到组件自己的选项中.
例子:
// define a mixin object
var my混合 = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [my混合]
})
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.
My插件.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(My插件)
现在,这些方法将随处可见.你可以看到这个here的例子.