Home > Net >  How can use computed for v-model?
How can use computed for v-model?

Time:12-22

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related