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" />
相关推荐
angerdream4 分钟前
Android手把手编写儿童手机远程监控App之agentweb如何实现全屏
前端
星栈13 分钟前
10 分钟跑起第一个 Dioxus 应用:`dx` CLI、`rsx!` 和热更新好不好用
前端·rust·前端框架
奋斗吧程序媛25 分钟前
补充一个小知识点:有关@click.native
前端·vue.js
英勇无比的消炎药34 分钟前
一行命令背后:TinyRobot CLI 如何重构 AI 对话接入的效率范式
vue.js·aigc
触底反弹35 分钟前
🚀 手把手用 HTML5 Canvas 从零打造飞机大战游戏,代码全开源!
前端·javascript·canvas
DJ斯特拉36 分钟前
axios快速使用
开发语言·前端·javascript
智通39 分钟前
可取消的异步任务与 AbortController
javascript
还有多久拿退休金39 分钟前
Ant Design Tree 搜索定位避坑指南:虚拟滚动下如何实现高亮与精准定位
前端·react.js
小月土星41 分钟前
CSS 3D 从入门到炫技:手把手教你写一个旋转立方体
前端·css
Hilaku1 小时前
AI 写代码越快,为什么 Code Review 越不能省?
前端·javascript·程序员