[toc]
## Mixins
Mixin (混入) 是一種可以在多個 Vue 組件之間靈活復用特性的機制。你可以像寫一個普通 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!"
~~~
更多細節請參見 API。
## 使用插件進行擴展
通常插件會為 Vue 添加一個全局的功能。
## 撰寫插件
你可以撰寫以下幾種典型類型的插件:
1. 添加一個或幾個全局方法。比如 vue-element
2. 添加一個或幾個全局資源:指令、過濾器、動畫效果等。比如 vue-touch
3. 通過綁定到 Vue.prototype 的方式添加一些 Vue 實例方法。這里有個約定,就是 Vue 的實例方法應該帶有 $ 前綴,這樣就不會和用戶的數據和方法產生沖突了。
~~~
exports.install = function (Vue, options) {
Vue.myGlobalMethod = ... // 1
Vue.directive('my-directive', {}) // 2
Vue.prototype.$myMethod = ... // 3
}
~~~
## 使用插件
假設我們使用的構建系統是 CommonJS,則需要作如下調用:
~~~
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 生成網絡請求、響應提供服務。
- vue-validator: 一個表單驗證的插件。
- vue-devtools:一個用來調試 Vue.js 應用程序的 Chrome 瀏覽器開發者工具擴展。
- vue-touch::添加基于 Hammer.js 的觸摸手勢的指令。
- vue-element: 用 Vue.js 注冊 Custom Elements。