vue2挂载全局方法/组件

Vue2 挂载全局方法/组件

  • 思路

    全局类的功能一般都写在main.js页面;

  • 需求

    把自己写的方法挂载到全局,这样每个组件都能使用了,比如下载方法

  • 代码

    js 复制代码
    // common.js 文件
    	// 通用下载方法
    	export function download(url) {
    	  window.open(baseURL + url)
    	}
    	
    js 复制代码
    // main.js
    import { download, } from "@/utils/common";
    //分页组件
    import Pagination from "@/components/Pagination";
    
    
    // 全局方法挂载
    	//下载
    	Vue.prototype.download = download  
    	//全局成功、错误提示、普通提醒
    	Vue.prototype.msgSuccess = function (msg) {
    	  this.$message({ showClose: true, message: msg, type: "success" });
    	}
    	
    	Vue.prototype.msgError = function (msg) {
    	  this.$message({ showClose: true, message: msg, type: "error" });
    	}
    	
    	Vue.prototype.msgInfo = function (msg) {
    	  this.$message.info(msg);
    	}
    
    //全局组件挂载
    	Vue.component('Pagination', Pagination) // 自己封装的分页组件挂载到全局
  • 使用

    js 复制代码
    // 全局方法的使用(在方法里直接调取就行)
    this.download(path)
    // 全局组件的使用(在模板template里直接用,全局组件不需要再单独引入了)
    <pagination :total="total" :page.sync="xxx" :limit.sync="xxx" @pagination="xxxonclick" />
相关推荐
雪隐12 分钟前
用Flutter做背单词APP-03为了给单词库塞满数据,我让AI给我打了上万份工
前端·人工智能·后端
hunterandroid13 分钟前
Android 安全最佳实践:从数据存储到网络通信的防护思路
前端
H Journey14 分钟前
web开发学习:html、css、js
前端·css·html·js
hunterandroid19 分钟前
Compose 性能优化:从卡顿到丝滑的实战经验
前端
hunterandroid23 分钟前
Kotlin Coroutines 在 Android 项目中的落地实战
前端
不一样的少年_31 分钟前
不用框架,手搓 AI Agent:(一) 先让它跑起来
前端·后端·agent
味悲31 分钟前
浏览器解析机制与XSS的15种编码绕过
前端·xss
小牛itbull40 分钟前
【译】为什么我使用 React 重构了 WordPress?
前端·react.js·重构
用户0595401744641 分钟前
AI Agent 记忆存储踩坑实录:这个问题让我排查了 3 天,最终用 pytest + Docker 实现秒级回归
前端·css
用户2986985301443 分钟前
在 React 中拆分 Excel 文件:从工作表到行列的实践
javascript·react.js·excel