The computed properties in Vue are not receiving any values when an array is passed using v-bind

Embarking on my Vue journey with a simple example, I am attempting to calculate the sum of items based on the provided data. If you wish to explore the complete example, it can be accessed in this jsffile.

Here is the component structure:

Vue.component('items-table', {
    props: ['items', 'item', 'total'],
    template: `
        <div>
                <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Price</th>
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="item of items"
                        v-bind:key="item.id"
                    >
                      <td>{{item.desc}}</td>
                      <td class="price">{{item.price}}</td>
                    </tr>
                </tbody>
            </table>
            
            
            <div>Total items: {{items.length}}</div>
            <div>Total price: {{total}}</div>
        </div>
    `
});

In the current implementation below, the console outputs an empty array, leading to always returning 0 as the total sum:

new Vue({
  el: '#app',
    data:{
        items: []
    },
    computed: {
        total: function(){
            console.log(this.items);
            return this.items.reduce(function(total, item){

                return total + item.price;
            },0);
        }
    },
    mounted() {
        console.log('app mounted');
    }
});

To start off, here is the initial set of data that will drive the display, manipulation, and calculations:

<div id="app">
  <items-table v-bind:total="total" v-bind:items="[
            { id: 1, desc: 'Banana', price: 10 },
            { id: 2, desc: 'Pen', price: 5 },
            { id: 3, desc: 'Melon', price: 5 }
        ]"></items-table>

</div>

The key challenge lies in the fact that the total displayed in {{total}} always registers as 0. It seems like the items array fails to update when passed via v-bind:items (could it be non-reactive?). Any assistance or insights would be greatly appreciated.

Edit: Additional Context

All data feeding into the components originates from plain PHP files. CRUD operations are currently not supported. Hence, it is crucial for the data to seamlessly bind directly from the tags.

Answer №1

Your function for calculating the total price is currently using an empty items object declared in the data tag of your view, resulting in a constant price of 0. To rectify this, consider implementing the following:

    new Vue({
  el: '#app',
    data:{
        items: [
            { id: 1, desc: 'Banana', price: 10 },
            { id: 2, desc: 'Pen', price: 5 },
            { id: 3, desc: 'Melon', price: 5 }
        ]
    },
    computed: {
        total: function(){
            console.log(this.items);
            return this.items.reduce(function(total, item){

                return total + item.price;
            },0);
        }
    },
    mounted() {
        console.log('app mounted');
    }
})

A more suitable Vue setup would resemble something like this:

    <div id="app">
  <h2>List of items</h2>
  <items-table v-bind:total="total" v-bind={items}></items-table>

</div>

This adjustment should assist you in resolving your issue.

Revision made by JSFiddle: https://jsfiddle.net/eywraw8t/210901/

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

Display a loading indicator or progress bar when creating an Excel file using PHPExcel

I am currently using PHPExcel to create excel files. However, some of the files are quite large and it takes a significant amount of time to generate them. During the file generation process, I would like to display a popup with a progress bar or a waitin ...

When a single object is modified in a JavaScript array, all the elements are affected

I am working with an array of 71 objects: var data = [] This array is populated with data from a database, containing both static and dynamic elements for each object in the data. angular.forEach(returnData,function(value,index) { if(!Array.isArray(va ...

Adding @submit.prevent conditionally to a form in Vue.js

I'm attempting to employ conditional prevention of HTML form submission using @submit.prevent. I have a simplified generic form model structured like this: <v-form v-model="valid"> <div> <div v-for="(field, i) i ...

Leveraging the power of Vue Draggable with a dynamic computed Array

I have been utilizing the vuedraggable component available at this link: https://github.com/SortableJS/Vue.Draggable The setup I am using is as follows: <draggable v-model="filteredItems"> <div class="item" v-for="item ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

Unable to engage with MUI stepper and modify a value

I am hoping to utilize an MUI stepper in place of a Select component. The current Select component is being utilized to signify the status of the document that the user is currently working on (New, In Progress, Complete, etc.). While I have successfully d ...

React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's applicat ...

Idle Time in Nextjs - Making the Most of D

I've been experiencing a significant delay of around 6 seconds when refreshing my Next.js platform. As part of my debugging process to identify the root cause of this issue, I uncovered that approximately 5 seconds of this time is classified as idle. ...

When an Axios response is received, the console logs an error message

Whenever I try to console.log(response) from json placeholder, an error message pops up stating that there is an "Unexpected console statement". Below is the code snippet: import axios from 'axios'; export default { name: 'app', ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class. Currently, when I am on the Home Page, the list item for Account Co ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

Iterate over a collection of JSON objects and dynamically populate a table with statistical data

In JavaScript, I am trying to dynamically generate a table with statistical data from an API that contains an array of JSON objects. The JSON data has a property called "score" which is interpreted as follows: score: 5 (excellent); score: 4 (very good); ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Customizing Images using a JSON array of images

Looking to implement a feature that displays images fetched from a CMS via a JSON file. The JSON data structure is as follows: { "images": [ {"title": "Image One", "url": "image1.jpg"}, {"title": "Image Two", "url": "image2.jpg"}, {"title": "Ima ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

Using the react-form library to create nested components with react.cloneElement

There is an issue that needs fixing with the library called react-form. Here is the error message I am currently facing: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ...