Mixin (混入) 是一種可以在多個 Vue 組件之間靈活復(fù)用特性的機制。你可以像寫一個普通 Vue 組件的選項對象一樣編寫一個 mixin:
// mixin.js
module.exports = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// test.js
var myMixin = require('./mixin')
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"
更多細節(jié)請參見 API。
通常插件會為 Vue 添加一個全局的功能。
你可以撰寫以下幾種典型類型的插件:
vue-elementvue-touchVue.prototype 的方式添加一些 Vue 實例方法。這里有個約定,就是 Vue 的實例方法應(yīng)該帶有 $ 前綴,這樣就不會和用戶的數(shù)據(jù)和方法產(chǎn)生沖突了。exports.install = function (Vue, options) {
Vue.myGlobalMethod = ... // 1
Vue.directive('my-directive', {}) // 2
Vue.prototype.$myMethod = ... // 3
}
假設(shè)我們使用的構(gòu)建系統(tǒng)是 CommonJS,則需要作如下調(diào)用:
var vueTouch = require('vue-touch')
// use the plugin globally
Vue.use(vueTouch)
你也可以向插件里傳遞額外的選項:
Vue.use(require('my-plugin'), {
/* pass in additional options */
})
vue-resource: 一個插件,為用 XMLHttpRequest 或 JSONP 生成網(wǎng)絡(luò)請求、響應(yīng)提供服務(wù)。vue-validator: 一個表單驗證的插件。vue-devtools:一個用來調(diào)試 Vue.js 應(yīng)用程序的 Chrome 瀏覽器開發(fā)者工具擴展。vue-touch::添加基于 Hammer.js 的觸摸手勢的指令。vue-element: 用 Vue.js 注冊 Custom Elements。下一節(jié): 最佳實踐與技巧。