Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's render, it works fine, but not when I go through a computed property.

I find this behavior surprising because I expected the computed property to be reactive as well. Can anyone shed light on why this might be happening?

Below is the snippet of code in question:

App.vue

<template>
  <div id="app">
    <Tester :testNumber="testNumber" />
  </div>
</template>

<script>
import Tester from "./components/Tester";

export default {
  name: "App",
  components: {
    Tester,
  },
  data() {
    return {
      testNumber: 1,
    };
  },
  mounted() {
    setTimeout(() => {
      this.testNumber = 2;
    }, 2000);
  },
};
</script>

Tester.vue

<template>
  <div>
    <p>Here is the number directly from the props: {{ testNumber }}</p>
    <p>
      Here is the number after passing through computed (doesn't update):
      {{ testNumberComputed }}
    </p>
  </div>
</template>

<script>
import { computed } from "@vue/composition-api";

export default {
  props: {
    testNumber: {
      type: Number,
      required: true,
    },
  },
  setup({ testNumber }) {
    return {
      testNumberComputed: computed(() => {
        return testNumber;
      }),
    };
  },
};
</script>

If you're interested, you can access a working codesandbox here.

While I do understand that using a watcher could solve this, I prefer to explore cleaner alternatives to address this challenge.

Answer №1

Avoid destructuring the prop to maintain its reactivity within the setup({ testNumber }) function:

setup(props) {
return {
  computedTestNumber: computed(() => {
    return props.testNumber;
  }),
};
}

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

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

I find the JSX syntax to be quite perplexing

While examining some code, I came across the following: const cardSource = { beginDrag(props) { return { text: props.text }; } }; When working with JSX block code or building objects, I usually use {}. The cardSource variable in this co ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

PHP seems to be resistant to receiving data from ajax requests

I am attempting to develop a drag and drop file upload feature without using a traditional form, utilizing JavaScript's FormData. However, I am encountering an issue where PHP does not seem to be receiving the uploaded file. Could there be some missin ...

"Uncaught Error: Unable to retrieve null properties" encountered while utilizing regex match in cheerio web scraping

Extracting text from brackets in HTML using regex: <dl class="ooa-1o0axny ev7e6t84"> <dd class="ooa-16w655c ev7e6t83"> <p class="ooa-gmxnzj">Cekcyn (Kujawsko-pomorskie)</p> </dd> <dd class="ooa-16w655c ev7e6t ...

What steps can I take to ensure my Vue website is tested on various devices and views before it goes live online?

My current project involves developing a website that utilizes Vue-js for the front-end, and Node + MySQL for the back-end. During development mode, when I connect to the internet and run npm run serve, I come across these lines in my command-line: https: ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Which specific jQuery functionality was made visible?

When it comes to jQuery, how is it exposed? // Expose jQuery to the global object window.jQuery = window.$ = jQuery; However, there are in fact two versions of jQuery: var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( s ...

Enhancing user experience with Ajax login forms that seamlessly integrate with browser password remember functionality

I recently implemented an ajax-based login form on my website, but it seems that browsers are not recognizing it as a login form and therefore not offering to remember passwords for easier login access. Once the submit button is clicked, the entered value ...

What sets the Event and EventHandler apart from each other in terms of functionality?

I am posting this question to gain clarity on the fundamental distinctions and practical applications of the Event versus EvenHandler. ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

Apigee Usergrid: Absence of bulk delete feature

Currently, I am utilizing usergrid for storage in a customer project. The data is divided into two collections: carShowrooms and cars. Thus far, everything has been running smoothly. However, there arises a situation where I need to refresh the masterdata ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

Starting the stored procedure/function using the sequelize.query() method

Below is the stored procedure I have written: CREATE OR REPLACE FUNCTION GetAllEmployee() RETURNS setof "Employees" AS $BODY$ BEGIN RETURN QUERY select * from "Employees"; END; $BODY$ LANGUAGE plpgsql; I am attempting to execute this stored procedure fro ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Is it possible to trigger a bootstrap modal-dialog without specifying an ID or class using JQuery or JavaScript?

Is there a way to work with Bootstrap modal-dialog without setting an id or class, perhaps using JQuery or JavaScript instead? <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstr ...

Transformer Class: An object containing properties that are instances of another class

class ClassA { x: number; y: number; sum(): number { return this.x + this.y; } } class ClassB { @Type(() => ClassA) z: {[key: string]: ClassA}; } const b = transformObject(ClassB, obj); const z = b.z[key]; const s = z.s ...

Prevent clicking on the <div> element for a duration of 200 milliseconds

I need to make this box move up and down, but prevent users from clicking it rapidly multiple times to watch it go up and down too quickly. How can I add a 200 millisecond delay on the click or disable clicking for that duration? View the jsfiddle example ...