VUE自己写方法并注册到组件里面。

比如myfunction.js文件

module.exports={ /* * 单一数组转根据ID和PID转日录树 * 用法,listToTree(array,{ *"idKey":"id",//id *"parentKey":"parent",//父ID *"children":"children"//子ID名 * }); * @date 数据组 * @options 格式化方法 传入 ID PID 和子目录名 */ //listToTree:function (data, options) { listToTree:function (data, {idKey='id',parentKey="pid",childrenKey='children'}={}) { /*options = options || {}; let ID_KEY = options.idKey || 'id'; let PARENT_KEY = options.parentKey || 'pid'; let CHILDREN_KEY = options.childrenKey || 'children'; */let tree = [],childrenOf = {},length = data.length; let item,id,parentId; for (let i = 0; i < length; i++) { item = data[i]; id = item[idKey]; parentId = item[parentKey] || 0; // every item may have children childrenOf[id] = childrenOf[id] || []; // init its children item[childrenKey] = childrenOf[id]; if (parentId != 0) { // init its parent's children object childrenOf[parentId] = childrenOf[parentId] || []; // push it into its parent's children object childrenOf[parentId].push(item); } else { tree.push(item); } }return tree; } //可以写多个方法或是自己定义变量。 }

【VUE自己写方法并注册到组件里面。】再到main.js里面注册
import myfunctionfrom './components/common/myfunction.js' Vue.prototype.$comFun = myfunction

在组件里直接调用
this.$comFun.listToTree(data);

这样就可以把自已经常会用的函数和值存在里面调用。但一定要保证调用时this指向的是VUE。

    推荐阅读