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>

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM