Steve Bauman
Steve Bauman

Reputation: 8678

Prevent a v-model change in Vue

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

Answers (2)

Visal
Visal

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

Bert
Bert

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

Related Questions