【由果索因】模块化代码后,这样的JavaScript技巧才值得用
一、背景
前端js
代码出现重复,因此想放到一个文件中进行复用,使其模块化,需要调整几个函数。函数都是要访问到后台接口的Axios
请求。
js
语法版本是ECMAScript6
。
前端功能是部门用户树形选择器,且选择器是懒加载模式。点击父节点请求到后台才会加载到子节点数据。
不止一个功能模块需要用到该部门用户树形选择器,因此,将重复的功能函数进行模块化。放到dept.js
文件中。
当前的文件就是直接在Vue
组件文件的method
中直接写需要用到的函数。
二、思路
2.1 树形选择器组件
看一下需要用到的属性,options
是数据,load-options
就是懒加载节点数据的函数。
<el-form-item label="负责人" v-permission="permission.select">
<treeselect
v-model="form.userId"
:options="depts"
:load-options="toLoadDepts"
style="width: 190px" placeholder="选择负责人" />
</el-form-item>
2.2 部门初始化数据函数改造
将初始化数据的函数放到dept.js
文件中。
//获取部门和员工数据
export function getDeptAndStaff(params) {
return request({
url: 'api/dept/getDeptAndStaff',
method: 'get',
params
})
}
//初始查询部门
export async function queryDepts() {
let depts = []
//每次只请求当前节点的所包含的下一级数据
await getDeptAndStaff({ enabled: true }).then(res => {
depts = res.content.map(function(obj) {
if (obj.hasChildren) {
obj.children = null
}
return obj
})
})
return depts
}
2.3 节点数据函数改造
//加载节点数据
export function loadDepts({ action, parentNode, callback }) {
if (action === LOAD_CHILDREN_OPTIONS) {
//根据父节点ID查询子节点数据
getDeptAndStaff({ enabled: true, pid: parentNode.id }).then(res => {
parentNode.children = res.content.map(function(obj) {
if (obj.hasChildren) {
obj.children = null
}
// if (String(obj.id).includes("staff")){
// delete obj.isDisabled
// }
return obj
})
setTimeout(() => {
callback()
}, 200)
})
}
}
2.4 导出引用
export default { queryDepts, loadDepts }
2.5 按需引用
import { queryDepts,loadDepts } from '@/api/system/dept'
2.6 在method中调用
async getDepts() {
//每次只请求当前节点的所包含的下一级数据
this.depts = await queryDepts()
},
toLoadDepts({ action, parentNode, callback }) {
loadDepts({ action, parentNode, callback})
}
三、几点疑问
- 直接在组件中写所需函数,请求到后台,就不需要同步
async
函数,而模块化后,就需要;
执行顺序的问题,虽然在mounted函数中取http请求的返回值取不到,但是不影响下拉框功能使用。 - 导出的函数也要加export
和export命令的用法有关,导出函数就是在其前加export