Reputation: 8678
I have a list of tasks stored in an array in my data()
method.
Is there a way I can prevent / reverse a change to an object when it's linked by a v-model
directive?
For example (in a component):
<template>
<tr v-for="task in tasks" :key="task.id">
<input @change="complete(task)" v-model="task.complete" type="checkbox" name="complete">
<td>{{ task.summary }}</td>
</tr>
</template>
<script>
export default {
props: ['allowChanges'],
data() {
return {
tasks: [],
};
},
methods: {
complete(task) {
if (this.allowChanges) {
// axios.post() etc.
} else {
// This doesn't work:
task.complete = !task.complete
}
},
}
}
</script>
I've tried using watchers and methods, but can't seem to reverse / cancel the change when made with a v-model directive?
Upvotes: 2
Views: 7147
Reputation: 477
You can simply use v-model.lazy to do this.
let vm = new Vue({
el: "#view",
data: {
data: "",
},
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="view">
<input type="text" v-model="data" placeholder="This is automatic" />
<input type="test" v-model.lazy="data" placeholder="Press Enter after writing">
<br>
<p>{{ data }}</p>
</div>
Upvotes: 0
Reputation: 82459
Disable the input when changes are not allowed.
<input @change="complete(task)" v-model="task.complete" type="checkbox" name="complete" :disabled="!allowChanges">
Upvotes: 4