插件能够让开发者提供的扩展看起来像是vue本身就有的。由于插件的功能会使用Vue全局对象或者实例来调用,或者被修改从而在Vue的钩子函数内起做用。好比用于http调用的插件vue-resource被插入到vue后,能够使用:javascript
Vue.http.get(url)html
的方式使用此插件提供的服务。本文构建一个能够执行的demo,验证插件对Vue的修改,代码以下:vue
var get = function(a){console.log('Hello ' +a)} var plugin = {} plugin.install = function(Vue) { if (plugin.installed) { return; } Vue.who = get; Object.defineProperties(Vue.prototype, { $who: { get() { return {get:get} } } }); Vue.mixin({ created: function () { console.log('Plugin activiated') } }) } if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(plugin); }
此插件以get函数形式提供服务,能够打印一个字符串。它必须公开一个对象,此对象有一个install的方法,此方法的参数为Vue,能够在此方法内经过赋值建立全局方法,像这样:java
Vue.who = get;
或者针对vue的prototype,经过defineProperties建立实例方法:函数
Object.defineProperties(Vue.prototype, { $who: { get() { return {get:get} } } });
混入能力能够把钩子函数混入到Vue实例内:vue-resource
Vue.mixin({ created: function () { console.log('Plugin activiated') } })
此时能够使用一个文件对它测试:测试
<html> <body> <script type="text/javascript" src="https://vuejs.org/js/vue.js"></script> <script type="text/javascript" src="p1.js"></script> <script type="text/javascript"> var vue = new Vue() vue.$who.get('Vue Instance') Vue.who('Global Vue') </script> </body> </html>
打开控制台,能够看到以下消息:url
Plugin activiated p1.js:2 Hello Vue Instance p1.js:2 Hello Global Vue