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>