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