Vue 使用Use、prototype自定义全局插件
Vue 使用Use、prototype自定义全局插件
by:授客 QQ:1033553122
开发环境
Win 10
node-v10.15.3-x64.msi
下载地址:
实现方式1
1. src目录下新建plugin目录
2. plugin目录下新建sendReuest.js
export function sendRequest() {
console.log("send request by sendRequet Plugin")
}
3. plugin目录下新建customPlugin.js
import * as customPlugin from"./sendRequest"
export default customPlugin
4. plugin目录下新建index.js
// 导入所有接口
import customPlugin from"./customPlugin"
const install = Vue=> {
if (install.installed) return// 如果已经注册过了,就跳过
install.installed = true
Object.defineProperties(Vue.prototype, {
// 注意,此处挂载在 Vue 原型的 $customPlugin对象上
$customPlugin: {
get() {
return customPlugin
}
}
})
}
export default install
关于Object.defineProperty
这个函数接受三个参数,一个参数是obj,表示要定义属性的对象,一个参数是prop,是要定义或者更改的属性名字,另外是descriptor,描述符,来定义属性的具体描述。
Object.defineProperty(obj, prop, descriptor)
5. 修改main.js
如下,新增带背景色部分的内容
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue"
import App from "./App"
import router from "./router"
import customPlugin from "@/plugin/index"
//等价导入方式
// import customPlugin from "@/plugin/"
// import customPlugin from "@/plugin "
Vue.use(customPlugin)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el:"#app",
router,
components: { App },
template:"<App/>"
})
6. .vue组件中引用
在.vue组件使用对应的插件调用sendReuqest方法
methods: {
sendRequest() {
this.$customPlugin.sendRequest();
}
},
注意:也可以在某些js中直接引入customPlugin,按customPlugin.sendRequest()的方式使用,笔者某次实践时这么使用:pluginName.fileModuleName.functionName(),发现会报错,提示fileModuleName为undefined,解决方法:采用Vue.prototype.$pluginName.fileModuleName.functionName()进行调用。
实现方式2
类似实现方式1,不同的地方在于:
1、去掉第4步
2、第5步,在main.js中添加的内容变成如下
import customPlugin from "@/plugin/customPlugin"
...略
Vue.prototype.$customPlugin = customPlugin
参考链接
作者:授客
微信/QQ:1033553122
全国软件测试QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限于时间仓促,文中可能存在错误,欢迎指正、评论!
作者五行缺钱,如果觉得文章对您有帮助,请扫描下边的二维码打赏作者,金额随意,您的支持将是我继续创作的源动力,打赏后如有任何疑问,请联系我!!!
微信打赏
支付宝打赏 全国软件测试交流QQ群
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签