Child Component in Vue Not Refreshing with Prop Update

I am currently working on updating an 'exercise' prop that is being sent to a 'workout' component in Vue. Within the child component, I have set up a function to emit and increment the current set you are on. The function is successfully triggering in the parent component (I can see console.logs()), however, the child component is not re-rendering.

Parent Component:

<ExerciseListItem
  v-for="(exercise) in exercises"
  v-on:completeSet="completeSet"
  v-on:selectExercise="selectExercise"
  v-bind:exercise.sync="exercise"
  v-bind:isActiveExercise="exercise.slug === activeExerciseSlug"
  v-bind:key="exercise.slug"
/>

Methods Used:

methods: {
  completeSet: function(slug) {
    console.log("complete-set", slug);
    const exercise = this.getExerciseBySlug(slug);
    exercise.completedSets++;
    if (exercise.completedSets === exercise.totalSets) {
      this.completeExercise(slug);
    }
  },
  completeExercise: function(slug) {
    this.getExerciseBySlug(slug).isComplete = true;
    console.log("COMPLETE-exercise", slug);
  },
  getExerciseBySlug: function(slug) {
    return this.exercises.find(exercise => exercise.slug === slug);
  },
  selectExercise: function(selectedSlug) {
    this.activeExerciseSlug = selectedSlug;
  }
},

Child Template:

<li
  v-bind:class="{ 'white-box': true, complete: exercise.isComplete }"
  v-on:click="exercise.totalSets > 1 ? $emit('selectExercise', exercise.slug) : $emit('completeSet', exercise.slug)"
>

You can find the project on Github here

Also, check out the live demo of the project

Your assistance would be greatly appreciated 😊

Answer â„–1

Your component is experiencing issues with updating because the nested values of your prop are not reactive, causing Vue to overlook their changes.

Effective Ways to Ensure Nested Properties Reactivity in Vue

This guideline applies to all state within your Vue application, whether it resides in a Vuex store, your data() function, or as part of a prop.

By default, Vue only establishes reactivity for declared state. This means that dynamically assigned state at runtime lacks reactivity (e.g., using mounted() { this.bar = 'two' } will not create a reactive property bar in your data()).

If you aim to establish dynamic reactivity for state, adhere to these two guidelines:

  1. All properties must be initialized using Vue.set(rootObject, key, value) (for example,

    mounted() { this.$set(this, 'bar', 'two') }
    - where this.$set() serves as an alias for Vue.set()). Further details can be found here: Vue Documentation

  2. Ensure arrays are manipulated using native array methods (Array.prototype.push(), etc.). Directly setting array elements by index does not induce reactivity in those elements. Note: Even Vue.set(rootArray, 1, value) will not suffice, as it sets the element based on index. Additional information can be accessed here: Common Vue Gotchas

Answer â„–2

You have the option to use this.$forceUpdate() in the parent component following the emit event, causing a re-render to occur.

The reason why your child component is failing to trigger the update automatically is uncertain at this time.

Answer â„–3

Although @MarcRo provided a correct answer, I would like to offer an additional solution because:

The main reason why the component is failing to update is due to the non-reactivity of the nested values in the prop. Vue is unable to detect these changes.

When you are modifying the object passed as a prop to the child component, using a deep copy can resolve this issue by ensuring that the entire object is updated rather than just a nested value.

One method for creating a deep copy of an object is as follows:

JSON.parse(JSON.stringify(object))

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

Transitioning from the login screen to the main page in Ionic with the help of Angular

My code is running smoothly, but I encountered an issue when clicking the login button. It changes the state as depicted in the image, altering the URL but failing to open the subsequent page. Can anyone provide guidance on how to redirect to the next page ...

Retrieving cached data using $http in AngularJS

When making a request to an API using $http in AngularJS, I am receiving cached results. Below is the AngularJS code snippet: $scope.validate = function(){ var encodedUserNameAndPassword = Base64.encode($scope.username + ':' + $scope.passwo ...

Error message: When using Sequelize.js with Node.js and Express.js, the Tasks.findAll() function results in a TypeError due to an undefined property being accessed

When trying to request /tasks, the code is supposed to return a JSON object with empty tasks. However, an error message is being returned instead - TypeError: cannot read property 'findAll' of undefined. The source of the error appears to be in r ...

React Native is facing difficulty in fetching pagination data which is causing rendering errors

Currently, I am working on fetching pagination data from an API. The process involves retrieving data from https://myapi/?page=1, then from https://myapi/?page=2, and so on. However, despite following this logic, I encountered an error that has left me puz ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

Experiencing the power of DoJo with the latest Wordpress 4

SOLUTION: After some investigation, I discovered that reordering the loading sequence of jQuery UI and DoJo files in the footer resolved the issue. By placing jQuery UI before any DoJo-related files, I ensured jQuery UI was fully loaded before any DoJo scr ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

React - The issue with my form lies in submitting blank data due to the declaration of variables 'e' and 'data' which are ultimately left unused

Currently, I'm working on incorporating a form using the react-hook-form library. Despite following the documentation and utilizing the handleSubmit function along with a custom Axios post for the onSubmit parameter like this: onSubmit={handleSubmit( ...

Using preventDefault in the compositionend event does not make any difference

var inputNode = document.getElementById('view_1'); inputNode.addEventListener('compositionend', function(e) { console.log(e.cancelable); // true e.preventDefault(); }); <div id="view_1" class="view" contenteditable="true> &l ...

How can I access an object in ng-model in AngularJS?

When a user selects a client from the list, I want to display the client's ID and country. Currently, I can display the entire selected object but not the specific client details. <label class="control-label red">Client</label> ...

Dynamic translation routing with Next.js

My goal is to create dynamic translation routes for specific pages in next js using i18next. While the following code works well, it currently routes to all pages and generates errors during next build. const router = useRouter(); const path = router.route ...

Twilio Group MMS feature experiencing technical difficulties

I currently have a Twilio Trial account with an active number that supports SMS/MMS. My goal is to use this number for group MMS chats, but I am facing some challenges. After following a tutorial on Tut, I attempted to create a basic test using the provid ...

Vue.js Asynchronous while loop (continuously checking backend until task completion)

When working inside a vue action, I am interested in continuously checking the status of my backend by calling another async action until a certain task is completed (there will be a loader on the frontend to show progress). To elaborate, I need to keep m ...

Having trouble with connecting to Gmail while using Nodemailer? Facing a Connection Timeout

Seeking assistance with sending emails through nodemailer. See below for the code snippet. var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<<a href="/cdn-cgi/l/email-protecti ...

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

Navigate to the Vuejs component's element that has a specified class name

When a component is loaded, I want it to automatically scroll down to display the element with a class name of 'actual-month' within an unordered list. <b-card no-body header="<i class='fa fa-align-justify'></i> Unorder ...

Using axios.spread() allows for caching of my API requests, a feature that is not available when

Thank you for taking the time to read this. I find myself in a peculiar situation where I am required to invoke multiple CMS API routes from my server to incorporate their response.data into an object that will later be transferred to the client side. The ...

Exploring the capabilities of Vue.js, including the use of Vue.set()

Just starting out with Vuejs and I have a query regarding the correct approach to achieve what I want. My Objective I aim to have some dates stored in an array and be able to update them upon an event trigger. Initially, I attempted using Vue.set, which ...

There appears to be a glitch preventing Phonegap from properly syncing with Google Analytics

I'm currently developing an app using PhoneGap and I wanted to integrate Google Analytics into it. After installing this plugin via the CLI, I inserted the following lines of code within my deviceReady event: analytics.startTrackerWithId('UA-*** ...