简体   繁体   中英

How can use computed for v-model?

I got data from API using computed. "UserModule.userInfo.usrEmail" is the state in my vuex. Like below:

data() {
    return {
      vModel: {
        email: {
          value: "",
        },
      }
   }
}

computed: {
   email:{
      get: function(){
        return UserModule.userInfo ? UserModule.userInfo.usrEmail : "";
      },
      set : function(email){
        this.vModel.email.value = email
      }
    },
 }

And then show it to user like below:

<input v-model="email"></input>

User can edit email and also cancel their edit process and return to their previous data but in edit everything was correct but when i want to cancel this process my previous data did not show in the input and i saw my new data which is not correct i want to cancel it. This is my cancel method on input:

resetInput(input) {
      this.vModel.email.value = this.email
    },

"this.email" refer to my computed which is get data from API.

How can i write this cancel process correctly and see my previous data in input tag?

this is because of your UserModule.userInfo.usrEmail .

this state does not update. your get in computed will be work when your UserModule.userInfo.usrEmail changes.

so you can use this solution:

data() {
  return {
    useGet :{
      email: true,
    },
  }
}

in your method:

resetInput(input) {
  this.useGet.email = true
},

and in your computed:

email: {
  get: function () {
    if (this.useGet.email) {
      return UserModule.userInfo ? UserModule.userInfo.usrEmail : ""
    }
    return ""
  },
  set: function (email) {
    this.useGet.email = false
  }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM