Home > Blockchain >  vue change value only after clicking submit
vue change value only after clicking submit

Time:04-17

I have a code like this. In this code, a user wants to change the current name. The current name is also displayed on top of the page.

<div>{{ currentUser.name }}</div>
<v-text-field
   required
   v-model="currentUser.name"
   
></v-text-field>

The data is from an API. Right now, if I change the value in the text field, the div value also changes. How to make it change only when the user already click (let's say) a submit button and the process succeed?

CodePudding user response:

This may work fine

<template>
  <div>
    <div>{{ currentUser.name }}</div>
    <v-text-field required  ref="textField"></v-text-field>
    <button @click="updateUsername">update user's name</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentUser: {
        name: '',
      },
    }
  },
  methods: {
    updateUsername() {
      this.currentUser.name = this.$refs.textField.internalValue
    },
  },
}
</script>

You could also use a debounce, store it in another state but having to use a $refs is okay here.

Also, I'm not a Vuetify user, hence I'm not sure what all of those value are about but you have some nice choice overall.

enter image description here

CodePudding user response:

Since Vuetify does not provide a lazy from to only allow value update on change event, you have to do it yourself. Use the :value prop and bind it to a computed property and provide a getter setter to the computed property.

This will only trigger the change on blur, when you click away from the input, or press enter or press tab.

<template>
  <div>{{ currentUserName }}</div>
  <v-text-field
     required
     :value="currentUserName"
     @change="onNameChange"
     
  ></v-text-field>
</template>

<script>
...

methods: {
  onNameChange(event) {
    this.currentUserName = event.target.value;
  }
}
computed: {
  currentUserName: {
    get() {
       return this.currentUser.name
    }, 
    set(newName) {
       this.currentUser.name = newName;   
    }
  }
}

...
</script>
  • Related