Updating values using events within a v-for loop in a Vue template: A step-by-step guide

Just starting out with Vue and Laravel!

Currently, I am retrieving data from an API Resource in Laravel.

The API consists of 2 fields:

Goal
Value

Here is the code snippet:

<template>
 <div class="container">
    <h1> Progress </h1>
       <div class= "progress" v-for = "progressdata in progress" v-bind:id="progressdata.id">
              <div>{{ progressdata.goal }}</div>
              <div id="div2">{{ progressdata.value }}</div>

        </div>
</div>
</template>

<script>

  export default {
    data: function() {
            return {
              progress: [],
              
           }
        },
 mounted() {
       this.loadContents();
       this.listen();
 },

methods: {
    loadContents: function() {

           //load Api
          
           axios.get('/api/progress')
           .then((response) => {
                this.progress = response.data.data;
               
         })
         .catch(function (error) {
           console.log(error);
    });
  },
    listen(){
      Echo.channel('progress')
          .listen('UpdatedValue', (e) =>{
            var target = e.target;
            console.log(target);
            var value = e.value;
            console.log(value);
            var div1 = document.getElementById(target);
            console.log(div1);
            div1.innerHTML = value;
            //console.log(e);

    });
    }
}
}
</script>

Output :

54974 -- Goal
6543 --value(Updated through tinker)
2   --Goal
1    --Value
463 --Goal
52   --Value

Encountering a challenge when triggering the event using Tinker:

event(new UpdatedValue('div2', 6543));

I have managed to update the value within the specific DIV with ID div2.

However, I need assistance in updating the entire array of Values in the v-for loop within the template when triggering events using Tinker.

Unsure about the next steps...Any help would be greatly appreciated!

Thank you.

Answer №1

Upon receiving the Event within Echo:

respond(){
      Echo.channel('progress')
          .listen('UpdatedValue', (e) =>{

            let UpdatedItem = this.progress.find(x => x.id === e.target)
            UpdatedItem.value = e.value;
            //console.log(e);

    });

Answer №2

One challenge with Vue's reactivity is that it doesn't automatically update nested properties. This means that if you change a value in a nested property, the change won't be reflected until something triggers a re-render.

A possible solution to this issue is to directly modify the array that the v-for directive is iterating over. By doing so, you can achieve the desired reactivity.

In order for this solution to work effectively, ensure that the event being triggered includes identifying information that matches the properties of the items in the progress array. In my example below, the event returns an object with the same properties as those in the progress array:

listen(){
    Echo.channel('progress').listen('UpdatedValue', (e) => {
        const idx = this.progress.findIndex((item) => {
            return item.id == e.id;
        });
        
        if (idx < 0) {
            this.progress.push(e);
        } else {
            this.progress.splice(idx, 1, e);
        }
    });

Answer №3

If you're looking to implement something similar, consider the following code snippet:

<template>
  <div class="container">
    <h1>Progress</h1>
    <div class="progress" v-for="p in progress" :key="p.id">
      <div>{{ p.goal }}</div>
      <div>{{ p.value }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      progress: [],
    };
  },
  mounted() {
    this.loadContents();
    this.listen();
  },
  methods: {
    loadContents: function() {
      axios
        .get('/api/progress')
        .then(response => (this.progress = response.data.data))
        .catch(error => console.log(error));
    },
    listen() {
      Echo.channel('progress').listen('UpdatedValue', progress => {
        // console.log(this.progress, progress);
        this.progress = this.progress.map(p => {
          // You should have something common here. May be id or any other key that you can compare to find the element in the progress array
          if (p.id == progress.id) {
            p.value = progress.value;
          }
          return p;
        });
      });
    },
  },
};
</script>

If this solution doesn't meet your requirements, uncomment the logging line and share the output with me for further assistance.

Replace

<div id="div2" v-html="progressdata.value"></div>
with
<div>{{ progressdata.value }}</div>
when updating numerical values without HTML elements.

For a live example, refer to this CodeSandBox link.

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

What is the best method to eliminate an invalid element from the DOM?

Below is the code snippet showing the xpaths where the value of $value can be found. We have noticed an abnormal tag td1 in the given URL (visible in the image) which is missing a closing tag. It seems like the developers intentionally placed it there, as ...

Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query const createUserClass = async (event) => { event.preventDefault(); try { const { data } = await createType({ ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...

Conceal particular table cells through jQuery

I am a beginner in the world of jQuery. My goal is to hide certain cells in a row when clicked, and have them displayed again when clicked once more. I've searched high and low for a solution, but all I find is how to hide entire rows. Here's an ...

When trying to insert glyphicons into a textarea, the result is displaying the actual text instead

When the glyphicon is clicked, I want the entered content to be added dynamically to the textarea. $(document).ready(function(){ //Click Event of glyphicon class $(document).on('click','.glyphicon',function(){ ...

The data event request in express using nodeJS is experiencing difficulties

I am currently facing an issue with the data event while trying to upload files using Express. Despite adding console logging tests, the data event doesn't seem to be working properly. Below is the server-side code snippet: var express = require(&ap ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Guide to turning off alerts for identifiers starting with an underscore (_)

Exploring ReactJS Development with ESLint Being a developer working with ReactJS, I find great value in the automated assistance provided by ESLint for detecting code issues like unused identifiers. If you're interested in experimenting with ESLint, ...

Having trouble setting up nginx in a container to reach a custom path location for a built vue app? If you're encountering a 404 error, here's how

I currently have a setup using Docker Swarm with a main nginx container that is accessible on ports 443 and 80. This nginx container acts as a proxy to a backend node application and a vue cli application housed within another nginx container. The setup is ...

Ways to recover HTML elements that have been eliminated by jQuery's remove

$(document).ready(function() { $('#remove').click(function() { $('.test').remove(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test-wra ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Javascript isn't being executed by Internet Explorer as expected

I'm currently working on a web application that requires backend processing while simultaneously showing the information on the screen. AJAX seems like the ideal solution, so I've implemented it in my project. However, before initiating the AJAX ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

zingcharts with multiple lines on x axis representing time

I am facing a rather interesting challenge with plotting data. I want to create a chart where time is the x-axis scale and multiple lines are plotted, each with varying time intervals between data points. While zingcharts has provided documentation on gene ...

AngularJS: The power of dynamic HTTP POST parameter names

Utilizing an API to update profile information allows for the addition of a nickname, email, phone number, or password in the request parameters, which will then be updated in the database. When updating a specific field, such as Nickname: { "nickname": ...

Create a Javascript dropdown menu with a validating calendar picker

My webpage has a drop-down menu that is dynamically generated via .jsp and filled with data from a database. However, I am having trouble with a JavaScript validation for two drop-down fields and two date pickers. Despite my limited JavaScript skills, I ne ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Saving the current date and time in PHP and JS to persist even after the browser has been closed

I am currently facing a situation where I can click on an image and it will display a new image. In the previous grid-item, it shows the day and time I clicked on it. What I want to achieve is to have this functionality persist even after closing and reop ...