如何以程序化的方式做到这一点

时间:2018-04-08 02:08:19

标签: vuejs2

我在vue.js应用程序中执行以下代码。我想以编程方式执行此操作以减少代码大小。

display_input(valu) {
            if(valu == 'editName') {
                this.editName = true
                this.editAddress = false
                this.editTelephone = false
                this.editEmail = false
            }
            if(valu == 'editAddress') {
                this.editName = false
                this.editAddress = true
                this.editTelephone = false
                this.editEmail = false
            }
            if(valu == 'editTelephone') {
                this.editName = false
                this.editAddress = false
                this.editTelephone = true
                this.editEmail = false
            }
            if(valu == 'editEmail') {
                this.editName = false
                this.editAddress = false
                this.editTelephone = false
                this.editEmail = true
            }
        },

2 个答案:

答案 0 :(得分:1)

使用以下内容,它可以全部压缩成:

display_input(valu) {
    this.editName = valu == 'editName'
    this.editAddress = valu == 'editAddress'
    this.editTelephone = valu == 'editTelephone'
    this.editEmail = valu == 'editEmail'
}

答案 1 :(得分:0)

这是我能想到的最短路,奖励是如果你添加任何属性,你就不需要改变它。

display_input(valu) {
    Object.keys(this).forEach(key => {
        this[valu] = valu == key
    })
}