<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="test">
<p v-my-directive="msg"></p>
</div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="../js/vue-myPlugin.js"></script>
<script type="text/javascript">
//声明使用插件,必须要加上这个声明
Vue.use(MyPlugin) // 内部会执行MyPlugin.install(Vue)
Vue.myGlobalMethod()
const vm = new Vue({
el: "#test",
data: {
msg: 'I Love You!'
}
})
vm.$myMethod();
</script>
</html>
vue-myPlugin.js
的内容
(function () {
// 需要向外暴露的插件对象
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.prototype.$myMethod = function () {
console.log('Vue实例对象的方法$myMethod')
}
}
//向外暴露
window.MyPlugin = MyPlugin;
})()