vue:设置全局函数以及调用函数

1、定义一个全局函数文件common.js,并定义全局函数

const token = '123456'

// 根据code得到name
const getNameByCode = (code, list, codeProperty, nameProperty) => {
  let name = '';
  if (code && Array.isArray(list)) {
    list.some((record) => {
      if (record[codeProperty] === code) {
        name = record[nameProperty];
        return true;
      }
      return false;
    });
  }
  return name;
};

export default{
  token,
  getNameByCode
}

2、绑定到vue上面:

在main.js文件上面,首先引入全局函数,并绑定的到vue上面。

import CommonFunction from './utils/commonFunction';   //引入文件

Vue.prototype.CommonFunction = CommonFunction;   // 绑定到vue上面

3、使用全局函数:

直接调用参数

token: this.CommonFunction.token

调用函数方法:利用code得到name

methods:{
  getName: function(parentId) {
     return this.CommonFunction.getNameByCode(
        parentId,
        this.roleTreeListResult,
        "id",
        "name"
      );
  }
}

在模板中调用函数方法

<template slot-scope="scope">
      <span v-if="scope.column.property === 'parentId'">
      {{ scope.row.parentId == 0 ? '顶级' : getName(scope.row[scope.column.property])}}</span> <span v-else>{{scope.row[scope.column.property]}}</span> </template>

  

原文地址:https://www.cnblogs.com/liumcb/p/13133612.html