Search code examples
javascriptvue.jsvuejs2vuex

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?


Solution

  • 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
      }
    },