How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiring me to import additional libraries for just one method.

My current setup is similar to the example provided below. However, as my list of data sources continues to expand, I am concerned about scalability. How should I structure the app to accommodate a potentially large number of sources? Any guidance would be greatly appreciated!

<template>
    <div>
        <h1>{{data.title}}</h1>
        <h2>{{data.subtitle}}</h2>
        <p>{{data.description}}</p>
    </div>
</template>

<script>
export default {
    data() {
            return {
                data: {}
            }
        },
        methods: {
            getFetchMethod() {
                var i = Math.floor(Math.random() * 3);
                if (i == 0) {
                    this.getData();
                } else if (i == 1) {
                    this.getDataThisWay();
                } else if (i == 2) {
                    this.getDataAnotherWay();
                } else {
                    this.getDataEtc();
                };
            },
            getData() {
                this.data = {
                    'title': 'Foo',
                    'subtitle': 'Bar',
                    'description': 'Blah'
                };
            },
            getDataThisWay() {
                this.data = {
                    'title': 'Foo',
                    'subtitle': 'Bar',
                    'description': 'Blah'
                };
            },
            getDataAnotherWay() {
                this.data = {
                    'title': 'Foo',
                    'subtitle': 'Bar',
                    'description': 'Blah'
                };
            },
            getDataEtc() {
                this.data = {
                    'title': 'Foo',
                    'subtitle': 'Bar',
                    'description': 'Blah'
                };
            }
        },
        mounted() {
            this.getFetchMethod();
        }
}
</script>

<style lang="css">
</style>

Answer №1

If you're working with VueJS, it's important to understand how to handle data effectively. One way to do this is by creating an array of objects, each containing its own data set. Then, you can use a random number as an index to access the data.

// Store all your data in an array
var datasets = [
    {
        title: 'Foo',
        subtitle: 'Bar',
        description: 'Blah'
    },
    {
        title: 'Foo2',
        subtitle: 'Bar2',
        description: 'Blah2'
    }
    // Add more objects here...
];

// Generate a random number based on the array length
var i = Math.floor(Math.random() * datasets.length);

// Use the random number as an index to retrieve data
this.data = datasets[i];

UPDATE: If you have multiple functions that retrieve data differently, you can organize them into an array and access them using indexes.

// Store method references in an array
var methods = [
    this.getData,
    this.getDataThisWay,
    this.getDataEtc
];

var i = Math.floor(Math.random() * datasets.length);

// Call a specific method based on the index
this.data = datasets[i]();

Furthermore, if your methods require a specific context, you can use the call() method to provide a different context than the default this.

this.data = datasets[i].call(this); // Use a specific context

Answer №2

To enhance the efficiency of our code, I would suggest creating a separate component for the template that accepts props like title, subtitle, and description. The parent component can then pass the required data to this child component based on how it retrieves the data.

Child.vue

<template>
    <div>
        <h1>{{title}}</h1>
        <h2>{{subtitle}}</h2>
        <p>{{description}}</p>
    </div>
</template>

<script>
export default {
    props: ["title", "subtitle", "description"]
}
</script>

Parent.vue

<template>
    <div>
        <button @click="way1">Way 1</button>
        <button @click="way2">Way 2</button>
        <child :title="title" :subtitle="subtitle" :description="description"></child>
    </div>
</template>

<script>
import Child from "./Child.vue"

export default {
    components:{
        Child
    },
    data(){
        return {
            title: "",
            subtitle: "",
            description: ""
        };
    },
    methods: {
        way1(){
            this.title="way 1 title";
            this.subtitle="way 1 subtitle"
            this.description="way 1 description"
        },
        way2(){
            this.title="way 2 title";
            this.subtitle="way 2 subtitle"
            this.description="way 2 description"
        }
    }
}
</script>

EDIT: It is also advisable to import a "data provider" into Parent.vue to handle data retrieval logic. This provider should return data in a defined format that can easily be passed to the child component.

Parent2.vue

<template>
    <div>
        <button @click="get">Get</button>
        <child :title="title" :subtitle="subtitle" :description="description"></child>
    </div>
</template>

<script>
import dataProvider from "./dataProvider"
import Child from "./Child.vue"

export default {
    components:{
        Child
    },
    data(){
        return {
            title: "",
            subtitle: "",
            description: ""
        };
    },
    methods: {
        get(){
            var data = dataProvider.get();
            this.title=data.title;
            this.subtitle=data.subtitle;
            this.description=data.description;
        }
    }
}
</script>

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

Determine how the scale of a transform changes over time by calculating the function of elapsed time [ transform: scale(x, y

I am currently working on a container that can be expanded and collapsed simply by clicking on a chevron icon. The functionality to collapse or expand the container resides within a function called transformAnimation. This function code closely resembles t ...

Breaking the link

My tabulator column contains text with line breaks that are displayed properly. However, when I use the built-in URL formatter, the line breaks disappear. {title:"Title", field:"title", formatter:"textarea"}, I attempted to add a link while maintaining t ...

Learning to implement a sliding effect on tab bar button click using Angular

When a user clicks on any tab button, I am using the transition effect "slide" to display the content. I have successfully implemented this in jQuery Mobile and you can see it in action in this fiddle: http://jsfiddle.net/ezanker/o9foej5L/1/. Now, I tried ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

accessing the offsetTop property of React elements

When working in React, I've noticed that the offsetTop value of an element differs between componentDidMount and componentDidUpdate. This is surprising to me because I believed componentDidMount occurs after render, meaning the DOM elements should be ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Building an array of objects using a foreach loop

i am struggling to create an array of objects from two input groups, each group consists of 3 inputs with data-side attributes set to left or right every input has a class named "elm" and a data-pos attribute set to a, b, or c <input class="elm-left elm ...

Is there a way to manipulate the src value using jQuery or JavaScript?

var fileref = document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", "http://search.twitter.com/search.json? q="+buildString+"&callback=TweetTick&rpp=50"); ...

Experiencing unexpected outcomes via AJAX requests

Linked to: Query Database with Javascript and PHP This inquiry is connected to my previous question. I made adjustments to the PHP script based on one of the responses I received; however, when attempting to utilize $.getJSON, I encountered difficulties. ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

What is the best way to implement an undo-list using arrays?

My current project involves creating a paint program in JavaScript, and I am aiming to implement an undo function rather than just an eraser. How can I store events in an array and then enable the deletion of each event individually? I have a dropdown men ...

My Vue build failed to incorporate the necessary function for outputting the .js file

While functioning properly in development mode, the build process seems to be excluding the setupToken function (from @/api.js) from the app.js output file. // App.vue //... import { setupToken } from '@/api export default { mounted () { this.se ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...

Is there a way to incorporate the image that was uploaded from the server onto an HTML page without using the file extension?

$('#userInfoPhoto').html(function () { return '<img src="../uploads/' + thisUserObject.profileimage + '" alt = "userphoto" style="width:250px; height:250px"/>' }); This script is essential for rendering images on th ...

Enhancing Octahedron Geometry in Three.js: Incorporating Materials Array

Is it possible to apply different materials to each face of a THREE.OctahedronGeometry? I have successfully done this with box objects, but when I try with THREE.OctahedronGeometry, I only see the first material on all faces. How can I achieve this with ...

Express encountered an unexpected error when attempting to navigate to the client directory

I am attempting to send the index.html file from my client directory, located at the same level as my server directory. However, I am encountering the following error: TypeError: undefined is not a function at Object.handle (/myapp/server/routes/routes.js ...

Encounter with Vue 3 - Uncaught ReferenceError: define is not a function

I'm encountering an issue while trying to test my component using Jest. Within the component, I have imported the @vue/apollo-composable library, and when running the test, I am getting the following error: ReferenceError: define is not defined ...