vue 自定义插件
https://www.cnblogs.com/shenjianping/p/11315839.html
1、插件的作用
- 插件通常会为 Vue 添加全局功能,一般是添加全局方法/全局指令/过滤器等
- Vue 插件有一个公开方法 install ,通过 install 方法给 Vue 添加全局功能
- 通过全局方法 Vue.use() 使用插件,它需要在你调用 new Vue() 启动应用之前完成.
2、开发插件并且使用
在项目目录下创建plugins.js文件,用于写入插件内容
(function () {
const MyPlugin = {} //声明一个插件对象
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
alert("添加全局方法或属性")
}
// 2. 添加全局资源
Vue.directive('my-directive', {
inserted: function (el, binding) {
el.innerHTML = binding.value
}
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
})
// 4. 添加实例方法,可以传参
Vue.prototype.$myMethod = function () {
alert('添加实例方法')
}
}
// 将插件添加到 window 对象中
window.MyPlugin = MyPlugin
})()
在index.html中进行引入,并且使用:
- 引入文件
<script src="./plugins.js"></script>
- 通过全局方法
Vue.use()使用插件
Vue.use(MyPlugin)
- 使用
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<button v-my-directive="msg"></button> <!--使用指令-->
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./plugins.js"></script>
<script>
Vue.use(MyPlugin)
var vm = new Vue(
{
el: '#app',
data: {
msg: 'hello'
},
// 在 `methods` 对象中定义方法
methods: {
}
}
)
//调用自定义的全局方法,Vue 调用
Vue.myGlobalMethod()
// 调用 Vue 实例方法,vm实例调用
vm.$myMethod()
</script>
</body>
</html>

浙公网安备 33010602011771号