Vue 3 sub-component failing to reflect changes in parent component data

I'm running into an issue with Vue 3. Whenever I update the data used to generate content in a subcomponent, the subcomponent fails to reactively update. I've been using the setup() function for the subcomponent, and I thought that props in Vue 3 are supposed to be reactive. I'm not sure where I might be making a mistake.

This is my parent component:

<q-markup-table :v-show="!isLoading">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(detailedPerson, index) in people" :key="index">
      <td>
        <PersonLink :person="buildPerson(detailedPerson)"></PersonLink>
      </td>
    </tr>
  </tbody>
</q-markup-table>

Here's the method being used:

  data() {
    return {
      people: {} as DetailedPerson[],
    };
  },
  methods: {
    buildPerson(detailedPerson: DetailedPerson): Person {
      return {
        slug: person.slug,
        firstName: person.firstName,
        lastName: person.lastName,
      };
    },
  }

Whenever the people list gets updated, the PersonLink component doesn't reflect the changes; it seems like the props aren't reacting accordingly. This is the code for the PersonLink component:

<template>
  <router-link :to="url">{{ name }}</router-link>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { NameFormatter } from 'src/common/formatters';
import { Person } from './person.models';

export default defineComponent({
  props: {
    person: {
      required: true,
      type: Object as () => Person,
    },
  },
  setup(props) {
    return {
      url: `/person/${props.person.slug}`,
      name: NameFormatter.formatInverseName(props.person),
    };
  },
});
</script>

What steps should I take to ensure reactivity when updating subcomponent props at the parent component level?

Answer №1

Reactivity in props allows for dynamic changes, but when creating static values from them, those values remain unchanged.

To ensure the url and name properties are updated, you need to utilize a computed reference as shown below:

import { defineComponent, computed } from 'vue';
setup(props) {
  const url = computed(() => `/person/${props.person.slug}`);
  const name = computed(() => NameFormatter.formatInverseName(props.person));

  return {
    url,
    name,
  };
}

Now, any changes in dependencies will automatically update both url and name, along with anything that relies on them.

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

Updating a value within destructuring and a loop: A step-by-step guide

My Goal: I aim to modify a value in an object that is part of an array element. Take a look at the code snippet below for a clearer understanding. An issue arises when I update the object's value through reference instead of creating a new copy, cau ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

Exploring AngularJS: A Guide to Accessing Millisecond Time

Is there a way to add milliseconds in Time using AngularJS and its "Interval" option with 2 digits? Below is the code snippet, can someone guide me on how to achieve this? AngularJs Code var app = angular.module('myApp', []); app.controller(&ap ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

What is the origin of this mysterious error?

I'm working on a function to format various types of variables and utilize a toString() method. It's handling complex objects, arrays, and circular references flawlessly. However, when testing it on a jQuery object using format($("body")) with l ...

Displaying additional users on my website using jQuery

Is it feasible for me to display the location of each logged-in user's <div> on a custom position on my page for other users to see? I would like to achieve this in (near) real-time if possible. Any guidance or suggestions on how to accomplish ...

What is the best way to prevent the table from being added again once it has been displayed?

I'm faced with the task of displaying an HTML table in a popup window when a button is clicked, using Bootstrap modal functionality. This scenario is similar to a preview function where user input is displayed in a table when a preview button is click ...

Looping through elements with jQuery's `each` method within another `

When using div containers in my code, I wanted to loop over them and then iterate through the items within each container. Instead of $('.stackContainer .stackItem').each(, I was looking for a solution like this: // setup stacks $('.stackC ...

Displaying column values in Vuetify Table based on a condition

https://i.stack.imgur.com/wK9uU.png I'm working with a Vuetify table that has a column for URLs. I need to implement logic to display either the URL or the URL Group name based on properties in my rules array. If rules[i].urlGroup is not empty, then ...

In Snowflake, SQL error handling block fails to execute

Implementing error handling in Snowflake using a Try Catch block has been my focus. I've enclosed SQL queries within JavaScript for this purpose. However, upon executing the query, I noticed that it skips the Try Catch block and directly executes the ...

Error: SyntaxError - Unexpected token 'if' found. Additionally, ReferenceError - berechnung is not defined

I keep encountering two error messages and I'm not sure where the issue lies: Uncaught SyntaxError: Unexpected token 'if' Uncaught ReferenceError: berechnung is not defined Any idea what might be causing this problem? I've reviewed t ...

What are the steps to fix the "Invariant Violation" issue that is linked to the redux store?

During my DOM testing to verify if a dialog box would open upon clicking a button, I encountered an error message: Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Creating an Angular directive that handles asynchronous attribute interpolation

I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page: <div my-directive user="{{user.name}}"></div> The user obje ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

Guide to updating current rjs files to incorporate jQuery and json in Rails 3

Currently, in my Rails 3 application, I am using rjs to render partials in my controllers. An example of this is when saving a new item to a table, the table gets refreshed: respond_to do |format| format.js { render :update do |page| ...

Does Vuex have a feature similar to mapDispatchToProps in Redux for managing actions and state?

In a child component, I found myself using this.updateData() instead of this.$store.dispatch(), with the updateData function being inherited from its parent component. Does anyone know how to accomplish this? ...

Tips for showcasing unprocessed JSON information on a webpage

Similar Question: JSON pretty print using JavaScript I am looking to present my raw JSON data on an HTML page similar to how JSONView displays it. Here is an example of my raw JSON data: { "hey":"guy", "anumber":243, "anobject":{ "whoa ...