Switch between toggling tasks in Vue does not seem to be functioning as

I'm reaching out again because I'm struggling to figure out what I'm doing wrong. I followed a tutorial step by step but the code isn't working as expected. My goal is to toggle between marking tasks as done and not done. When I test the code, nothing happens and there are no error messages. I've tried reading the documentation, but it's still unclear to me. I'm relatively new to programming.

 let bus = new Vue();

    let Task = {
       props: ['task'],
     template: `
    <div class="task" :class="{ 'task--done' : task.done , 'task-notdone' : task.done === false }">


      {{ task.body }}
      <a href="#" v-on:click.prevent="toggleDone(task.id)">Mark me as {{ task.done ? 'not done' : 'done' }}</a>

    </div>
    `,

    methods: {
      toggleDone(taskId) {
        bus.$emit('task:toggleDone', taskId);
       }
    }

    };

    let Tasks = {
       components:{
         'task': Task
       },

       data() {
    return {
      tasks: [
        {id: 1, body: 'Task One', done: false },
        {id: 2, body: 'Task Two', done: true },
        {id: 3, body: 'Task Three', done: true }
      ],
    }
      },

       template: `
  <div>
  <template v-if="tasks.length">
  <task v-for="task in tasks" :key="task.id" :task="task"></task>
  </template>
      <span v-else>No tasks</span>
              <form action="">
                 form
              </form>
         </div>
           `,

      methods: {
    toggleDone(taskId){
      let task = this.tasks.find(function (task) {
        return task.id === taskId;
      });

      console.log(task);
    }
       },

       mounted () {
    bus.$on('task:toggleDone', (taskId) => {
      this.toggleDone(taskId);
    })
     },
    };

    let app = new Vue({
      el:'#app',
      components: {
        'tasks': Tasks,

      },


    });

Answer №1

It seems unnecessary that the tutorial suggested using a bus in this scenario. The tasks are javascript objects, with each task object passed to the task component. Since it is an object and not a primitive value, you can easily update the done property within the task component.

console.clear()

let Task = {
  props: ['task'],
  template: `
    <div class="task" >
      <span :class="{ 'task--done' : task.done , 'task-notdone' : !task.done}">{{ task.body }}</span>
      <a href="#" v-on:click="task.done = !task.done">Mark me as {{ task.done ? 'not done' : 'done' }}</a>
    </div>
  `
};

let Tasks = {
  components:{
    'task': Task
  },
  data() {
    return {
      tasks: [
        {id: 1, body: 'Task One', done: false },
        {id: 2, body: 'Task Two', done: true },
        {id: 3, body: 'Task Three', done: true }
      ],
    }
  },
  template: `
    <div>
      <template v-if="tasks.length">
        <task v-for="task in tasks" :key="task.id" :task="task"></task>
      </template>
      <span v-else>No tasks</span>
    </div>
  `,
};

let app = new Vue({
  el:'#app',
  components: {
    'tasks': Tasks,
  },
});
.task--done{
  text-decoration: line-through
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67111202275549524955">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <tasks></tasks>
</div>

In addition, if you prefer not to change the object within the component, you have the option to emit an event that allows the parent to modify it instead.

console.clear()

let Task = {
  props: ['task'],
  template: `
    <div class="task" >
      <span :class="{ 'task--done' : task.done , 'task-notdone' : !task.done}">{{ task.body }}</span>
      <a href="#" v-on:click="$emit('toggle-task', task)">Mark me as {{ task.done ? 'not done' : 'done' }}</a>
    </div>
  `
};

let Tasks = {
  components:{
    'task': Task
  },
  data() {
    return {
      tasks: [
        {id: 1, body: 'Task One', done: false },
        {id: 2, body: 'Task Two', done: true },
        {id: 3, body: 'Task Three', done: true }
      ],
    }
  },
  template: `
    <div>
      <template v-if="tasks.length">
        <task v-for="task in tasks" :key="task.id" :task="task" @toggle-task="toggleTask"></task>
      </template>
      <span v-else>No tasks</span>
    </div>
  `,
  methods:{
    toggleTask(task){
      task.done = !task.done
    }
  }
};

let app = new Vue({
  el:'#app',
  components: {
    'tasks': Tasks,
  },
});
.task--done{
  text-decoration: line-through
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d4d7c7e2908c978c90">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <tasks></tasks>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Screen white on the right side

I am encountering an issue where my screen shows white on the side when I scroll to the right. I am unsure how to remove it and cannot locate the problem in the code. Here is a link to the code: https://jsfiddle.net/y3j01hbt/ In the provided code, there i ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...

Flying around in every essential element within a Vue template

Recently, I made the switch to Typescript for Vue and decided to enable the Volar extension. However, after doing so, I noticed that every HTML intrinsic element (such as section and img) is now being flagged as an error: JSX element implicitly has type &a ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue w ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

The image source is visible in Vue.js, but unfortunately, my picture is not showing up

Below is the code and script that I have: <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> ...

Code for asynchronous routing in Node.js

My current setup involves using node with express version 4.0, and I've noticed a lack of information online (including in the documentation) regarding embedding asynchronous code within a route. With middleware, it's straightforward: app.use(& ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Discover the steps to integrating jsfiddle into my local development environment

If you want to check out the code for this example, head over to jsfiddle at this link. And below is a snippet of the HTML file: <!DOCTYPE html> <html> <head> <script src="http://www.jacklmoore.com/colorbox/jquery.colorbox.js" type= ...

The ng-app feature is causing the script to run endlessly

Currently, I am troubleshooting an issue within my angular application that is built on the asp.net web application empty template. The problem arises when I utilize ng-app; if I leave it blank, the $routeProvider fails to initialize. However, if I specify ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

Eliminate the flickering effect on the dropdown menu

Is there a way to eliminate the annoying 'flicker' effect on my menu? Whenever I click on 'Dropdown 1', I notice that Test 1 and Test 2 flicker. My assumption is that this is due to my use of the !important declaration. Any suggestion ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

Meteor JS: How can I effectively manage the state of a unique template?

I'm currently delving into the realms of Session and reactive data sources within the Meteor JS framework. They prove to be quite useful for managing global UI states. However, I've encountered a challenge in scoping them to a specific instance o ...