VUE课程---24、插件
一、总结
一句话总结:
vue里可以自定义插件,在插件里可添加全局方法和属性、添加全局指令、添加实例方法等等操作。
(function (window) { const MyPlugin={}; MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或属性 Vue.myGlobalMethod = function () { console.log('Vue函数对象的myGlobalMethod()') }; // 2. 添加全局资源 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { el.textContent = 'my-directive: '+binding.value; } }); // 4. 添加实例方法 Vue.prototype.$myMethod = function (methodOptions) { console.log('vm实例方法$myMethod()') }; }; window.MyPlugin = MyPlugin; })(window);
1、vue使用插件注意?
vue使用插件要声明使用的插件,例如Vue.use(MyPlugin)来声明使用vue的MyPlugin插件,这在内部会调用插件对象的install()方法
Vue.use(MyPlugin); // 内部会调用插件对象的install() Vue.myGlobalMethod(); //调用MyPlugin插件全局的myGlobalMethod方法 vm.$myMethod(); //调用MyPlugin插件实例的$myMethod方法
二、插件
博客对应课程的视频位置:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>插件</title> 6 </head> 7 <body> 8 <!-- 9 10 --> 11 <div id="app"> 12 <p>{{msg}}</p> 13 <p v-my-directive="msg"></p> 14 </div> 15 <script src="../js/vue.js"></script> 16 <script src="vue-myPlugin.js"></script> 17 <script> 18 // 声明使用插件(安装插件: 调用插件的install()) 19 Vue.use(MyPlugin); // 内部会调用插件对象的install() 20 //MyPlugin在插件内部已经暴露给了window,所以可以直接用 21 22 let vm = new Vue({ 23 el: '#app', 24 data: { 25 msg: '我有一只小毛驴,我永远也不骑' 26 } 27 }); 28 //console.log(vm); 29 //console.log(Vue.myGlobalMethod); 30 Vue.myGlobalMethod(); //调用MyPlugin插件全局的myGlobalMethod方法 31 vm.$myMethod(); //调用MyPlugin插件实例的$myMethod方法 32 </script> 33 </body> 34 </html>
插件:vue-myPlugin.js
1 (function (window) { 2 const MyPlugin={}; 3 MyPlugin.install = function (Vue, options) { 4 // 1. 添加全局方法或属性 5 Vue.myGlobalMethod = function () { 6 console.log('Vue函数对象的myGlobalMethod()') 7 }; 8 9 // 2. 添加全局资源 10 Vue.directive('my-directive', { 11 bind (el, binding, vnode, oldVnode) { 12 el.textContent = 'my-directive: '+binding.value; 13 } 14 }); 15 16 17 // 4. 添加实例方法 18 Vue.prototype.$myMethod = function (methodOptions) { 19 console.log('vm实例方法$myMethod()') 20 }; 21 }; 22 window.MyPlugin = MyPlugin; 23 })(window);