TransWikia.com

Vue Js Dynamic Class Binding Not Updating

Stack Overflow Asked by Niall Parker on January 24, 2021

I’ve been learning Vue Js with the customary todo app.

I’m binding a class to my todo objects based on the truthy value of todo.completed as below:

    <a v-bind:class="{iscomplete : todo.completed}">
    <input type="checkbox" v-on:change="markComplete" />

The iscomplete class simply adds a line through text decoration.

The checkbox calls the following method:

methods: {
    markComplete() {
      this.todo.completed = !this.todo.completed;
    }

The above works for any todo items already in the DOM but when new todos are added the dynamic class binding no longer works.

I’ve included a short gif below showing the issue.

I can’t seem to find any answers, perhaps my lack of experience with Vue is leading me to search for the incorrect terms. I do apologise if it has been asked before I can’t seem to get my head around it/find similar issues online.

Can anyone explain the theory behind why this might fail like this?enter image description here

2 Answers

Okay, turns out the methods work fine for new elements injected into the DOM. I had used the property 'complete' to 'false' instead of 'completed' when construction my new todo object.

    prepareTodo: function () {
      const newTodo = {
        id: Math.random(2),
        description: this.todoDescription,
        complete: false,
      };

Therefore when the method was firing it was updating a property that shouldn't exist and isn't referenced.

Answered by Niall Parker on January 24, 2021

make the method as computed

computed: {
    markComplete() {
      this.todo.completed = !this.todo.completed;
    }

The method works for data that you have after refresh page. computed listens for any changes that might have the variable ;)

Answered by LastM4N on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP