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

Animated jQuery carousel with a timer countdown feature

Currently, I am developing a jquery slider/carousel to display various promotions. I am seeking a method to indicate the time left until the next promotion appears. Similar to the flash promo on this website: Do you have any suggestions? ...

What is the proper way to incorporate a ref within a class component?

I am encountering an issue with my class component. I'm wondering if there is a comparable feature to useRef() in class components? Despite several attempts at researching, I have yet to find a solution. ...

Trouble with image display in a next.js project hosted on Firebase

Exploring Next.js for the first time, I recently created a website and attempted to host it on Firebase hosting. Everything seems to be working well except for one issue - the images are not rendering on the hosted site. In my project structure, there are ...

What are some ways to sort through JSON data efficiently?

I am in need of filtering JSON data based on specific parameters. When using the GET method at http://localhost:5000/api/car?bodyTypeId=2, I expect to receive only JSON objects with bodyTypeId equal to 2. However, all objects are being returned: [ { ...

When I use the AngularJS otherwise function, it sends me to the incorrect route

My routes are defined in the following way: $routeProvider .when('/settings', { templateUrl: 'settingsTemplateURL', controller: settingsCtrl }) .when('/profile', { templateUrl: 'profileTemplateURL', controll ...

What is the quickest way to find and add together the two smallest numbers from a given array of numbers using JavaScript?

const getSumOfTwoSmallestNumbers = (numbers) => { const sortedNumbers = numbers.sort((a, b) => a - b); return sortedNumbers[0] + sortedNumbers[1]; } I encountered this challenge on Code Wars. My function to find the sum of the two smallest num ...

Error [ERR_MODULE_NOT_FOUND]: Module could not be located in vscode

Issue with VS Code: Module Not Found Error View the image associated with the erroreN.png ...

In MongoDB, learn the process of efficiently updating nested objects in a dynamic manner

We have a variety of nested configurations stored in MongoDB. Initially, we store the following object in MongoDB: const value = { 'a': { 'b': 1 } } collection.insertOne({userId, value}) Now, I would like to modify the object in ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Transform a string into an object using AngularJS $parse function

Imagine having a server that sends back a response in the form of: { multiply:function(x,y) { return x*y; }, divide:function(x,y) { return x/y; } } Can this be converted into a functional method? I attempted to convert ...

Display the menu and submenus by making a request with $.get()

My menu with submenu is generated in JSON format, but I am facing issues displaying it on an HTML page using the provided code. Can someone please assist me in identifying what mistakes I might be making? let HandleClass = function() { ...

unable to implement multiple layouts while utilizing react-router

My current project requires two different layouts: one for the homepage (currently implemented in app.js) and another for the result page. After submitting a form, the results should be displayed in the result layout instead of the app layout. However, whe ...

What is the process for restarting the timer within a timer controlled by the react-countdown component?

Looking for guidance on how to implement a reset() function in ReactJS and JavaScript to reset a timer when the "Reset Clock" button is clicked on my webpage. The goal is to have the timer return to its initial value. Open to suggestions on how to achieve ...

Is it possible to use Javascript to retrieve a variable from a remote PHP file?

I am trying to retrieve a variable from a remote PHP file using JavaScript in my phonegap application. The same origin policy doesn't apply here, so I believe I need to use JSON/AJAX for this task. However, I have been unable to find any tutorials tha ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

Is it possible to incorporate additional sections by utilizing map and props in the given code snippet?

I have a component named CardItems.jsx which specifically defines the appearance of a card. Then, I also have Gotocart.jsx where there is a welcome section (similar to welcoming someone to their cart) and an order section at the end (for initiating an orde ...

Running a script upon service initialization

Can code be run when a service is first initialized? For instance, if the product Service is being initialized, I'd like to execute the following code: this.var = this.sharedService.aVar; ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...