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" />
相关推荐
Lee川6 分钟前
从零构建现代化登录界面:React + Tailwind CSS 前端工程实践
前端·react.js
Awu12276 分钟前
⚡精通 Claude 第 1 课:掌握 Slash Commands
前端·人工智能·ai编程
竹林8186 分钟前
从ethers.js迁移到Viem:我在重构DeFi前端时踩过的那些坑
前端·javascript
码云之上11 分钟前
上下文工程实战:解决多轮对话中的"上下文腐烂"问题
前端·node.js·agent
小小弯_Shelby13 分钟前
webpack优化:Vue配置compression-webpack-plugin实现gzip压缩
前端·vue.js·webpack
小村儿19 分钟前
连载04-CLAUDE.md ---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
攀登的牵牛花26 分钟前
我把 Gemma4:26b 装进 M1 Pro 后,才看清 AI 编程最贵的不是模型费,而是工作流
前端·agent
前端郭德纲27 分钟前
JavaScript Object.freeze() 详解
开发语言·javascript·ecmascript
大漠_w3cpluscom28 分钟前
现代 CSS 的新力量
前端
魏嗣宗34 分钟前
Claude Code 启动的那 200 毫秒里发生了什么
前端·claude