Skip to content

Instantly share code, notes, and snippets.

@renaco
Created February 27, 2023 14:07
Show Gist options
  • Save renaco/68f2e41d60d721a8899079bbb9a842d1 to your computer and use it in GitHub Desktop.
Save renaco/68f2e41d60d721a8899079bbb9a842d1 to your computer and use it in GitHub Desktop.
How to avoid vue model
How to avoid refresh data with v-model vue?
When you use v-model in Vue, it automatically updates the data whenever the input value changes. This behavior can be useful in many cases, but in some situations, you may want to avoid refreshing the data. Here are some approaches to achieve that:
Use a computed property:
You can create a computed property that calculates the value based on the input value, instead of directly binding the input to the data property. This way, the data property won't be updated every time the input changes.
Example:
php
Copy code
<template>
<div>
<input v-model="inputValue">
<p>{{ computedValue }}</p>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: '',
}
},
computed: {
computedValue() {
// Calculate the value based on the input value
return this.inputValue.toUpperCase();
}
}
}
</script>
Use a debounce function:
You can use a debounce function to delay the data update until the user has stopped typing for a certain period of time. This way, the data won't be updated every time the user types a new character.
Example:
php
Copy code
<template>
<div>
<input v-model="inputValue" @input="updateData">
<p>{{ dataValue }}</p>
</div>
</template>
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
inputValue: '',
dataValue: '',
}
},
methods: {
updateData: debounce(function () {
// Update the data value after a delay of 500ms
this.dataValue = this.inputValue.toUpperCase();
}, 500)
}
}
</script>
Use a watch property:
You can use a watch property to watch for changes in the input value and update the data property only when necessary.
Example:
php
Copy code
<template>
<div>
<input v-model="inputValue">
<p>{{ dataValue }}</p>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: '',
dataValue: '',
}
},
watch: {
inputValue(newValue) {
// Update the data value only when the input value changes to a certain value
if (newValue === 'update') {
this.dataValue = this.inputValue.toUpperCase();
}
}
}
}
</script>
These are some ways to avoid refreshing data with v-model in Vue. You can choose the one that best suits your needs depending on your use case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment