美文网首页
Vue批量全局引入js及对应方法

Vue批量全局引入js及对应方法

作者: Vincent_Rain | 来源:发表于2020-11-13 23:01 被阅读0次

俗话说每个人都有自己的小工具,项目中经常会频繁调用小工具方法,频繁引入很费时间,因此此文介绍下如何批量全局引入js

1. 创建方法

在正确位置创建自己的js文件,比如src下创建一个utils.js文件

里面创建多个方法,比如:parseTime、getFileType

/**
   * @param {string} url
   * @returns {Object}
   */
  export function param2Obj(url) {
    const search = url.split('?')[1]
    if (!search) {
      return {}
    }
    return JSON.parse(
      '{"' +
        decodeURIComponent(search)
          .replace(/"/g, '\\"')
          .replace(/&/g, '","')
          .replace(/=/g, '":"')
          .replace(/\+/g, ' ') +
        '"}'
    )
  }
/**
   * @param {string} filePath
   * @returns {string}
   */
  export function getFileType(filePath) {
    var startIndex = filePath.lastIndexOf(".");
    if(startIndex != -1)
      return filePath.substring(startIndex+1, filePath.length).toLowerCase();
    else return "";
  }

2. 添加到Vue全局方法中

main.js中引入,添加

// 全局注册小工具
import * as utils from './utils';
Vue.prototype.$utils = utils;

划重点:一定要import * as

3. 愉快使用

在需要用到的组件中,果断抽出来遛一遛
let fileType = this.$utils.getFileType(this.fileUrl)

相关文章

网友评论

      本文标题:Vue批量全局引入js及对应方法

      本文链接:https://www.haomeiwen.com/subject/lgxibktx.html