1.自定义插件
- Vue 插件是一个包含 install 方法的对象
- 通过 install 方法给 Vue 或 Vue 实例添加方法, 定义全局指令等
2.编码
插件(vue-myPlugin.js)
/**
* 自定义vue插件
*/
(function () {
const MyPlugin = {}
MyPlugin.install = function (Vue, options) {
//1、添加全局方法或属性
Vue.myGlobalMethod = function () {
alert("Vue函数对象方法执行")
}
//2、添加全局资源
Vue.directive('my-directive', function (el, binging) {
el.innerHTML = "MyPlugin my-directive " + binging.value
})
//3、添加实例方法
Vue.prototype.$myMethod = function () {
alert('vue实例对象方法执行')
}
}
window.MyPlugin = MyPlugin
})()
插件测试(test.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>14-自定义插件</title>
</head>
<body>
<div id="app-14">
<!--使用自定义指令-->
<p v-my-directive="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="./vue-myPlugin.js"></script>
<script type="text/javascript">
//使用自定义插件
Vue.use(MyPlugin)
var vm = new Vue({
el: '#app-14',
data: {
msg: '自定义插件'
}
});
//调用自定义静态方法
Vue.myGlobalMethod()
//调用自定义实例方法
vm.$myMethod()
</script>
</body>
</html>
评论