js代码优化,求助!
总是感觉能优化一下,各位大佬帮忙看看
1.下面是element按钮组二次封装后的组件
<my-btn-group class="mr-50-px"
btnSize="mini"
:btnList="timeTypeList"
@myClick="timeTypeClick"
></my-btn-group>
<my-btn-group
class="mr-50-px"
btnSize="mini"
:btnList="statusTypeList"
@myClick="statusTypeClick"
></my-btn-group>
<my-btn-group class="mr-50-px" btnSize="mini" :btnList="typeList" @myClick="typeClick"></my-btn-group>
<my-btn-group btnSize="mini" :btnList="statusTimeList" @myClick="statusTimeClick"></my-btn-group>
2.对应的js
// 按钮组 时间export const timeTypeList = [
{ label: "全部 ", value: "ALL", type: "timeTypeList" },
{ label: "今年 ", value: "JN", type: "timeTypeList" },
{ label: "去年 ", value: "QN", type: "timeTypeList" },
{ label: "前年 ", value: "QYN", type: "timeTypeList" }
];
// 按钮组 数量金额
export const typeList = [
{ label: "数量 ", value: "number", type: "typeList" },
{ label: "金额 ", value: "money", type: "typeList" }
];
// 按钮组 执行状态
export const statusTypeList = [
{ label: "全部 ", value: "ALL", type: "statusTypeList" },
{ label: "执行中 ", value: "ZXZ", type: "statusTypeList" },
{ label: "已完结 ", value: "YWJ", type: "statusTypeList" },
{ label: "已终止 ", value: "YZJ", type: "statusTypeList" },
{ label: "已中止 ", value: "YZJ2", type: "statusTypeList" }
];
// 按钮组 时间状态
export const statusTimeList = [
{ label: "全部 ", value: "ALL", type: "statusTimeList" },
{ label: "已延期 ", value: "YQ", type: "statusTimeList" },
{ label: "正常 ", value: "ZC", type: "statusTimeList" }
];
对应的几个方法
timeTypeClick(item) { this.TimeType = item.value
this.getProjectClass()
},
typeClick(item) {
this.Type = item.value
this.getProjectClass()
},
statusTypeClick(item) {
this.statusType = item.value
this.getProjectClass()
},
statusTimeClick(item) {
this.statusTime = item.value
this.getProjectClass()
},
这几个方法有点重复代码,能不能封装一下呢,封装一下是不是好点,
我想下面这样,把这几个方法写到一个里面,但是有问题,按钮组切换的时候,对应的还是初始化的数据,不是切换后的,难搞,大佬们帮忙看看,希望给个思路
btnGroupClick(item) { debugger
let constType = {
timeTypeList: function () {
this.TimeType = item.value
},
typeList: function () {
this.Type = item.value
},
statusTypeList: function () {
this.statusType = item.value
},
statusTimeList: function () {
this.statusTime = item.value
},
}
constType[item.type]()
console.log(this.TimeType, item.value) // this.TimeType输出没有变化,总是初始时的ALL
this.getProjectClass()
},
回答:
搞明白了,原来是this指向出了问题
btnGroupClick(item) { let constType = {
timeTypeList: () => (this.timeType = item.value),
typeList: () => (this.type = item.value),
statusTypeList: () => (this.statusType = item.value),
statusTimeList: () => (this.statusTime = item.value),
}
constType[item.type]()
this.getProjectClass()
},
回答:
按钮组切换的时候,对应的还是初始化的数据,不是切换后的,难搞
这个可以使用vue的$nextTick解决。
另外封装的事情,我觉得问题不大,如果觉得每个按钮组的组件修改一个data值繁琐,可以把formadata的data放到store中,通过向按钮组传入formdata的key值,在按钮组组件中修改值。按钮事件还是需要emit回父组件,因为可能每一个按钮组在修改值后所要处理的逻辑不仅仅是修改formdata参数。
以上是 js代码优化,求助! 的全部内容, 来源链接: utcz.com/p/935986.html