I have a code like this. In this code, a user wants to change the current name. The current name is also displayed at top of the page.
// template
<div>{{ currentUser.name }}</div>
<v-text-field
required
v-model="currentUser.name"
class="mb-3"
></v-text-field>
<v-btn>submit</v-btn>
//script
data() {
currentUser: null
},
methods: {
getUser(id) {
//my GET method here
},
updateUser() {
//my PUT method here
}
The data is from an API. The current v-text-field is filled with the current name. 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 has already clicked (let's say) a submit button and the process succeed?
This may work fine
<template>
<div>
<div>{{ currentUser.name }}</div>
<v-text-field required class="mb-3" 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.
Adding on to Kissu's answer, if you wish to change the value on blur (when you click away), you have to do the following.
Since Vuetify does not provide a lazy prop 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"
class="mb-3"
></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>
<div>{{ currentUser.name }}</div>
<v-text-field
required
:value="currentUser.name"
@input="nameChanged" //here maybe @change="xxx"
class="mb-3"
></v-text-field>
<v-btn @click="updateUser">submit</v-btn>
//script
data() {
currentUser: null
},
methods: {
nameChanged(e) {
console.log(`e`,e) //The value is based on the printed value
this.tempName = e
},
updateUser() {
this.currentUser.name = this.tempName
}
}