(尚017)Vue插件

1.如何开发插件?

2.编写自己的vue-myPlugin.js插件库,代码如下:

/**
* vue的插件库
* 最好使用匿名函数包裹起来,这样代码会更加规范
* 里面的实现被隐藏
*/
(function(){
//MyPlugin是个变量,需要定义
//需要向外暴露的插件对象
const MyPlugin={}
//插件对象必须有一个install()方法
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
console.log('Vue函数对象的方法myGlobalMethod()')
}

// 2. 添加全局资源,意思就是自定义指令
Vue.directive('my-directive', function(el,binding){
el.textContent=binding.value.toUpperCase()
})

// 4. 添加实例方法
//怎样给Vue的实例添加方法?实例方法放在原型对象上,原型对象上的方法实例会看的见
//如何找到原型对象?通过函数的显示原型属性指向原型对象
//因为函数原型对象上有方法myGlobalMethod,实例上也有方法,怎样区别?通过添加$区别
Vue.prototype.$myMethod=function(){
console.log('Vue实例对象的方法$myMethod()')
}
}
//向外暴露插件
window.MyPlugin=MyPlugin
})()
3.编写test017.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="test">
<p v-my-directive="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<!--插件库应该在vue.js下面,要不自己定义的插件库没法用-->
<script type="text/javascript" src="../js/vue-myPlugin.js"></script>
<script type="text/javascript">
//声明使用插件,需要在自己写的插件库中向外暴露
//相当于把插件安装上,你想用别人的插件库,下面这句必须有
Vue.use(MyPlugin) //内部会执行MyPlugin的install方法并传入参数Vue,即:MyPlugin.install(Vue)

Vue.myGlobalMethod()

const vm=new Vue({
el:'#test',
data:{
msg:'吾乃常山赵子龙也!'
}
})
vm.$myMethod()
</script>
</body>
</html>
4.运行截图

原文地址:https://www.cnblogs.com/curedfisher/p/12026877.html