What could be the reason behind the failure of this computed property to update in my Vue 3 application?

As I transition from Vue's Options API to the Composition API, I decided to create a small Todo App for practice.

Within App.vue, my code looks like this:

<template>
  <div id="app">
    <ErrorMessage
      v-if="!isValid"
      message="The todo body must be at least 3 characters long"
    />

    <SuccessMessage v-if="allDone" message="You can relax now! :)" />

    <p>{{ allDone }}</p>

    <div class="card">
      <Header />
      <List
        :todos="todos"
        @delete-todo="deleteTodo"
        @toggle-todo="toggleTodo"
      />
      <AddTodo @add-todo="addTodo" />
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import ErrorMessage from './components/ErrorMessage.vue';
import SuccessMessage from './components/SuccessMessage.vue';
import Header from './components/Header.vue';
import List from './components/List.vue';
import AddTodo from './components/Add.vue';

export default {
  name: 'App',
  components: {
    ErrorMessage,
    SuccessMessage,
    Header,
    List,
    AddTodo,
  },

  setup() {
    const todos = ref([]);
    const isValid = ref(true);
    const allDone = ref(false);

    return { todos, isValid, allDone };
  },

  methods: {
    toggleTodo: function (index) {
      this.todos[index].done = !this.todos[index].done;
    },
    deleteTodo: function (index) {
      if (confirm('Are you sure?')) {
        this.todos.splice(index, 1);
      }
    },
    addTodo: function (text) {
      let newTodo = {
        done: false,
        text: text,
      };

      if (text.length > 2) {
        this.isValid = true;
        this.todos.push(newTodo);
      } else {
        this.isValid = false;
      }
    },
  },

  computed: {
    allDone: function () {
      // Check if there are todos and
      // If all of them are done
      let undoneTodos = this.todos.filter((todo) => todo.done === false);
      return this.todos.length && !undoneTodos.length;
    },
  },
};
</script>

In my code, I utilize the computed property allDone to determine if all todos are completed. When conditions are met, a success message ("You can relax now!") should display in an alert component.

Despite this logic, the initial value of the allDone variable remains unchanged even when conditions warrant it to change. What could be causing this issue?

Answer №1

To avoid the ref overshadowing the computed property, it is recommended to eliminate the allDone from the setup function return.

Another approach would be to define it as a computed property within the setup and exclude it from the computed option:

setup(){
  const todos = ref([])
  const allDone = computed(() => todos.value.length > 0 && todos.value.every(todo => todo.done))
  ...
  return {todos, allDone, ...}
}

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

Tips for sending multiple JSON objects using the ajax() method

As of now, I have successfully implemented a $.getJSON() call to fetch a JSON string from a specific URL. Here is the simplified code that is currently functioning well: $.getJSON("myURL",function(data){ var receivedJSON = data; }); The retrieved JSO ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

What is the best way to show an on/off button in an HTML page when it loads, based on a value stored in a MySQL database?

Is there a way to display a toggle button onload based on a value from a MySQL database table? I need the button to switch between 0 and 1 when clicked. I've looked at several solutions but none of them seem to work for me. Any help would be greatly a ...

Can the pointerover event be managed on a container within the am5 library?

While attempting to add an HTML label to a map and trigger a pointerover event, I encountered issues. The objective was to change the HTML content upon hover. Despite trying to incorporate a tooltip, the hover event failed to work properly, and the tooltip ...

There are errors occurring in the getter I created within the vuex store.js file

Currently utilizing vuejs, vuex, and vuetify. Within this project there are 3 files in play and I will share the key sections here. The main objective is to showcase data associated with the route parameter. Despite my attempts in Product.vue as shown bel ...

What is the best way to transform a GET request with a query string into a promise?

After successfully making a request with querystring params, I encountered an issue while trying to promisify my request: // Works var Promise = require("bluebird"); var request = Promise.promisifyAll(require("request")); request.get({ url: 'htt ...

Is it possible to utilize Vue-I18n without the need for a build process?

If I want to use Vue2 without any build step, is it possible to incorporate Vue-I18n in the same way? <!doctype html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Utilizing interactions between a JavaScript scrollable container and Python/selenium

My goal is to utilize Selenium/Python in order to automate the process of downloading datasets from . While I am new to Javascript, I am determined to learn and overcome any obstacles that may arise during this project. Currently, I am focusing on the init ...

I am experiencing an issue with the checkbox in my React app where the state is not updating after it has been

I am currently building a todo app using React, but I'm encountering an issue where nothing happens when I click the checkbox. I've provided my code below: App.js import './App.css'; import React from 'react' import TodoItem ...

What is the best way to import scss files and images in Vue.js storybook stories?

In this component, I am importing an image using src="@/assets/images/logo.png" with the help of @ for addressing: <template> <div class="loading_container"> <img class="loading_logo" src="@/assets/ ...

The sequence of HTML attributes

Could there be a subjective angle to this question (or maybe not)... I work on crafting web designs and applications using Visual Studio and typically Bootstrap. When I drag and drop a CSS file into an HTML document, the code generated by Visual Studio loo ...

"Organizing a menu in JSON format based on alphabetical

After following this guidance, I successfully created a JSON menu. However, the items are currently sorted by ID and I am in need of sorting them alphabetically. I am unsure about whether using array.sort(); would be applicable in this scenario. Check out ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

What are the steps for utilizing a button instead of an input field that is not within a form?

I need assistance with setting up a navbar with a button that will submit a form in the body with the ID of album_form. Can anyone provide suggestions for what to include in the onclick attribute to achieve this functionality? <body> <header& ...

Learn the best way to send query parameters through the Next.js navigation router and take advantage of

Currently, I am implementing import { useHistory } from 'react-router-dom' const history = useHistory() ... history.push('/foo?bar=10') However, only the 'foo' part is being pushed into the url. What is the correct way to pas ...

The Ajax request is successfully looping through multiple files, however, it is not properly sending them to the server. As a result, only one file

I have been working on an ajax request that successfully retrieves information about files, such as the number of files, their names, and looping through them. Now, I am faced with the challenge of saving these files to a local folder on my computer. I hav ...

Full-screen modal fade not functioning properly

I am trying to implement multiple fullscreen modals on a single page, but I am facing an issue where they slide in and out at an angle instead of just fading in and out. I have been unable to achieve the desired effect of a simple fade transition. If you ...

Regular intervals and asynchronous JavaScript and XML (AJAX) requests are

There is a simple chat tool in place to ensure the chat room stays updated: setInterval (loadLog, 2500); function loadLog(){ //Scroll height prior to the request var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20; ...

This phrase cannot be invoked

My code seems correct for functionality, but I am encountering an error in my component that I do not know how to resolve. Can someone please help me with this issue? This expression is not callable. Not all constituents of type 'string | ((sectionNa ...