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" />
相关推荐
倾颜44 分钟前
从 textarea 到 AI 输入框:用 Tiptap 实现 / 命令、@ 引用和结构化请求
前端·langchain·next.js
kyriewen2 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen3 小时前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
yuzhiboyouye4 小时前
web前端英语面试
前端·面试·状态模式
canonical_entropy5 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月5 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅5 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆5 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong6 小时前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee6 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php