Vue插件

Vue插件

插件作用

插件通常用来为 Vue 添加全局功能

例如:
1、添加全局资源:指令/过滤器/过渡等。如 vue-touch
2、通过全局混入来添加一些组件选项。
3、添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
4、一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

开发

Vue官方规定插件必须暴露一个install方法,方法第一个参数为Vue实例

// myPlugin.js
export default function install (Vue) {
Vue.prototype.$plugin = 'myPlugin'
}
// 或者
export default myPlugin = {
install (Vue) {
Vue.prototype.$plugin = 'myPlugin'
}
}
// main.js
import myPlugin from '@/plugins/myPlugin'
Vue.use(myPlugin) // 作用:调用myPlugin中install方法

插件示例

使用插件方式封装 element-ui messageBox,实现全局页面内调用

// dialogPlugin.js
export const dialogPlugin = {
install(Vue) {
function dialog({
text,
confirm,
cancel,
confirmButtonText = '确定',
cancelButtonText = '取消',
type = 'warning',
title = '提示',
center = false
}) {
if (!text) {
throw new Error(`text is require`)
}
Vue.prototype.$confirm(text, title, {
confirmButtonText,
cancelButtonText,
type,
center
}).then(() => {
confirm && confirm()
}).catch(() => {
cancel && cancel()
})
}
Vue.prototype.$dialog = dialog
}
}
// main.js
import { dialogPlugin } from '@/plugins/dialog';
Vue.use(dialogPlugin)
// index.vue
this.$dialog({ text: 'xxxxx xxxx', title: 'xxxx', confirm: () => { console.log('xxx') } })

posted on   吴知木  阅读(78)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示