全局函数的使用

298 阅读1分钟

在项目中的时候可能会碰到难道,有一个功能很多地方都会用得到,为了减少代码的冗杂程度,这时候我们可以把这个函数写到全局中,当成全局函数来使用 1.全局函数

export const changeFun = function (value, data){
  // 输出:键和值互相转换的实例
const initData = {
    1: "我",
    2: "爱",
    3: "你",
  } 
  // 输出:根据值查到的对应的键
  for (let [key, item] of Object.entries(initData)) {
    if (item === value) {
      return key;
    } else if (item instanceof Object === true) {
      return this.getKey(value, item);
    } else if (item === undefined || item === null) {
      return item;
    }
  }

}

2.项目中的应用

1)引入函数
import {changeFun} from "@/common";
2)使用函数
change: changeFun('变量')