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" />
相关推荐
xiaofeichaichai3 分钟前
前端安全 XSS 与 CSRF
前端·安全·xss
JS菌11 分钟前
Skills 动态加载系统:让 AI Agent 按需获取领域知识
前端·人工智能·后端
weedsfly13 分钟前
Sass 代码复用完全指南:从变量到模块化
前端
张拭心18 分钟前
Android 17 新特性:后台音频交互限制加强
android·前端
张拭心27 分钟前
Android 17 新特性:ProfilingManager 新触发器
android·前端
黄敬峰35 分钟前
从 XMLHttpRequest 到 JSON 模拟:打通前后端通信的任督二脉
javascript
weixin_4713830335 分钟前
Taro-03-页面生命周期
前端·javascript·taro
张拭心39 分钟前
Android 17 新特性:MessageQueue 无锁实现
android·前端
Asize41 分钟前
数组数据结构底层:从灵活到陷阱
前端·javascript·算法