Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself.

I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "items" property.

const app = new Vue({
    data: {
        taxRate: '',
        to: '',
        from: '',
        items: ''
    },
    created: function () {
        fetch('https://example.netlify.com/invoicedetails.json')
        .then(resp => resp.json())
        .then(items => {
            this.items = items
        })
    }
    });

Below is the code snippet necessary for extracting partial data:

new Vue({    
    data: {
    taxRate: .13,
    to: [
        'University of Somewhere',
        '118 Bureaucracy Lane',
        'Cityville, CA 90210',
    ],
    from: [
        'Business Time Inc.',
        '60 Paycheck Drive',
        'Townsland, ON A1B 2CD',
        'Canada',
    ],
    items: [
        [1, `Amazing product you can't live without`, 549],
        [3, `Unnecessary extra item`, 49],
    ]
    },
    template: `
    <div class="min-h-screen bg-gray-700 p-8 text-gray-900">
        <div class="max-w-4xl mx-auto">
        <div ref="quote" class="bg-white px-12 py-20">
            <h1 class="uppercase font-bold text-gray-600 text-3xl border-b pb-8">Quote</h1>
            <div class="mt-8 flex -mx-6">
            <div class="w-1/2 px-6">
                <div class="text-gray-700 font-bold text-sm mb-2">To:</div>
                <div v-for="line in to">{{ line }}</div>
            </div>
            <div class="w-1/2 px-6">
                <div class="text-gray-700 font-bold text-sm mb-2">From:</div>
                <div v-for="line in from">{{ line }}</div>
            </div>
            </div>
            <table class="w-full mt-8">
            <thead>
                <tr>
                <th class="px-4 py-4 border-b text-right">Quantity</th>
                <th class="px-4 py-4 border-b text-left">Description</th>
                <th class="px-4 py-4 border-b text-right">Price</th>
                <th class="px-4 py-4 border-b text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="[quantity, description, price] in items">
                <td class="px-4 py-4 border-b text-right">{{ quantity }}</td>
                <td class="px-4 py-4 border-b text-left">{{ description }}</td>
                <td class="px-4 py-4 border-b text-right">{{ price | price }}</td>
                <td class="px-4 py-4 border-b text-right">{{ price * quantity | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Subtotal</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ totalWithoutTaxes | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Taxes</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ taxes | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Total</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ total | price }}</td>
                </tr>
            </tbody>
            </table>
            <div class="mt-8 text-center text-gray-700">
            All prices in USD.
            </div>
        </div>
        </div>
    </div>
    `,
    el: '#app',
    computed: {
    totalWithoutTaxes() {
        return this.items.reduce((total, [quantity, _, price]) => {
        return total + (quantity * price)
        }, 0)
    },
    taxes() {
        return this.totalWithoutTaxes * (1 + this.taxRate) - this.totalWithoutTaxes
    },
    total() {
        return this.totalWithoutTaxes + this.taxes
    },
    },
    filters: {
    price: function (value) {
        return `$${value.toFixed(2)}`
    }
    }
})

Access the CodePen here

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

Perpetual duplication of data occurs upon inserting an item into the Array state of a React component

Whenever a new item is added to the React JS Array state, data duplication occurs. console.log(newData) The above code outputs a single object, but when you print the actual data with console.log(data) You will notice continuous duplicates of the same da ...

Troubleshooting sequential image loading in KineticJS and resolving issues with opacity tween when setting fillPatternImg

In my latest project using KineticJS, I am developing a small app that generates multiple nodes in the form of RegularPolygons. Once the stage has loaded (activated with play();), I proceed to sequentially fill each node with an image pattern using loadIma ...

Iterate through each key in the response JSON object using a variable named "a

Here is a snippet of my code: var roomid= roomIds[i] const Availabilitydata = await AvailResponse.json(); availableroomsArray.push(Availabilitydata); app.get("/api/availability", (req, res) => { res.json({ indicateur: availableroomsA ...

Passing an array of objects as properties in React components

My functional component looks like this: function ItemList({ items }: ItemProps[]) { return <p>items[0].name</p> } Here is how I'm creating it: <ItemList items={items} /> The array items contains objects in the format [{name: &ap ...

Guide to creating a React Hooks counter that relies on the functionality of both a start and stop button

I am looking to create a counter that starts incrementing when the start button is clicked and stops when the stop button is pressed. Additionally, I want the counter to reset to 1 when it reaches a certain value, for example 10. I have tried using setInte ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

Storing information in the DOM: Choosing between Element value and data attribute

When it comes to storing values in a DOM element, we have options like using the data attribute. For example, $("#abc").data("item", 1) can be used to store values and then retrieve them with $("#abc").data("item"). However, I recently discovered that th ...

Experiencing a memory drain issue with your Android application?

I have a straightforward Android application that fetches JSON data from a PHP file on my local server. It was running smoothly until recently when it started encountering issues, which I suspect might be due to a memory leak – though I'm not entire ...

Extract the content inside an HTML <a> tag with a specified class and auto-populate it into a different text area

I found an HTML tag that is being generated by a WordPress plugin and it contains a random link. My goal is to automatically retrieve this generated link and place it in a textarea within a contact form. The generated code with the link (cannot be modifie ...

A guide to sharing session variables with express views

Struggling to access session variables in EJS views and encountering various challenges. To locally access req.session, I've implemented middleware as outlined in this guide on accessing Express.js req or session from Jade template. var express = re ...

What is the best way to show an array object from PHP to AJAX in JavaScript?

I am facing an issue with a function that returns an array object from PHP using MySQL. I need to call this array in an AJAX function using JavaScript, but I am unsure of how to display the PHP array object in a dynamic table or console log. Here is my PH ...

Exploring the utilization of props in single file components with Vue.js

Just starting out with vue.js, I'm utilizing single file components in conjunction with webpack. I am attempting to calculate the sum of {{operating.totaloperating}}. From what I've gathered, I need to pass the data back to the script as a prop, ...

Decoding JSON Data in Angular 2

I am facing a challenge where I have an array of JSON objects that need to be parsed into my Tournament class. The Tournament class has the following structure: export class Tournament { constructor (public id: number, public name: string, ...

Sending data via PHP using the JSON format

I have developed a program that extracts post values and converts them into a JSON encoded array. Everything was functioning perfectly until I was instructed to submit the form data with a content-type of application/json. Ever since then, I have been un ...

Dropdown element vanishes upon selecting in HTML

Utilizing Angular's ng-init to populate a rest call function and populate $scope.races before filling up the dropdown. Initially, everything appears to be working correctly. However, upon selecting an option from the dropdown menu, it immediately cle ...

Converting unstructured text to JSON format

I am facing a challenge with a string that appears as follows: {"name": "john", "smith", "paul", "address": "nyc", "chicago", "age": 50, 60} My objective is to transform this into JSON in the following format: {"name": ["john", "smith", "paul"], "addres ...

What is the best way to handle the return value from using indexOf on a string?

I am looking to manipulate the value returned by a specific conditional statement. {{#each maindata-hold.[2].qa}} <div class="section"> <a href="javascript:void(0)" class="person-link" id="{{id}}"> <span class="name- ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...