Loading various elements based on multiple parameters in Vue.js 2: The ultimate guide

My API consists of endpoints that return lists of JSON objects:

/api/data/foo
/api/data/bar
/api/data/fizz

In my single-page application, I have a table and a dropdown selector:

<select v-model="tableChoice">
    <option selected>Foo</option>
    <option>Bar</option>
    <option>Fizz</option>
</select>

<table class="table table-hover">
    <thead>
        <tr>
            <th v-for="header in tableHeaders">
                {{ header }}
            </th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="record in tableData" :key="record.recordId">
            <td v-for="element in record">{{element}}</td>
        </tr>
    </tbody>
</table>

I currently have three separate Vue components with their own API URLs and table headers:

var fooLink = 'api/foo';

new Vue({
    el: '#app',
    data: {
        tableHeaders:["Record ID","Record Name", "Record Detail"],
        tableData: null,
        dataChoice: 'Foo'
    },
    methods:{
        getFooData: function(){
            this.$http.get(fooLink).then(function(response){
                this.tableData = response.data;
            }, function(error){
                console.log(error.statusText);
            });
        }
    },
    mounted: function () {
        this.getFooData();
    }
});

I am looking to use a single table or component where the API URL used is determined by the tableChoice variable. How can I achieve this without clear documentation on conditional loading with props?

Answer №1

<select v-model="tableChoice">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="orange">Orange</option>
</select>

Implement a select box change handler.

new Vue ({
    el: '#app',
    data: {
        tableData: null,
        tableChoice: 'apple'
    },
    computed: {
        apiUrl() {
            switch (this.tableChoice) {
                case 'apple': return '/api/data/apple';
                case 'banana': return '/api/data/banana';
                case 'orange': return '/api/data/orange';
            }
        },
        tableHeaders() {
            switch (this.tableChoice) {
                case 'apple': return ['Apple'];
                case 'banana': return ['Banana'];
                case 'orange': return ['Orange'];
            }
        },
    },
    watch: {
        tableChoice() {
            this.getFruitData();
        },
    },
    methods: {
        getFruitData() {
            this.$http.get(this.apiUrl).then(response => {
                this.tableData = response.data;
            }, error => {
                console.log(error.statusText);
            });
        }
    },
    mounted() {
        this.getFruitData();
    }
});

Answer №2

To implement this functionality, follow the steps below:

<select v-model="selectedOption">
    <option v-for="item in items" v-bind:value="item.id">
        {{ item.name }}
      </option>
</select>

<table class="table table-striped">
    <thead>
        <tr>
            <th v-for="col in columns">
                {{ colName }}
            </th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="row in data" :key="row.id">
            <td v-for="item in row">{{ item.value }}</td>
        </tr>
    </tbody>
</table> 

Javascript Code:

new Vue ({
    el: '#app',
    data: {
        columns:["ID","Name", "Description"],
        data: null,
        selectedOption: this.items[0].id},// default value
        items: [
            {name: 'Item 1', id: '/api/item/1'},
            {name: 'Item 2', id: '/api/item/2'},
            {name: 'Item 3', id: '/api/item/3'}
        ]
    },
    methods:{
        fetchData: function(url){
            this.data = null;
            this.$http.get(url).then(function(response){
                this.data = response.data;
            }, function(error){
                console.log(error.message);
            });
        }
    },
    mounted: function () {
        this.fetchData(this.selectedOption);
    },
    watch: {
        selectedOption(newValue){
            this.fetchData(newValue);
        }
    }
});

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

Issue with Iconify icon not updating when "data-icon" is set using setAttribute()

I'm having trouble trying to animate or replace an icon using the "setAttribute" method. Can someone take a look at my code and help me figure out what's wrong? <!DOCTYPE html> <html> <script src="https://code.iconify.design/1/1 ...

The next-auth/discord callbacks do not make any changes to the data

Currently, I am utilizing the next-auth/discord and facing an issue with the session callback not setting the user id to the session property as expected. [...nextauth].js import NextAuth from "next-auth/next"; import DiscordProvider from " ...

Unable to retrieve image: status code 402 - payment required

When trying to fetch my Facebook page's posts using the Facebook graph API and nextjs with vercel, I encountered an error: GET imageurl 402 payment required. Oddly enough, this works perfectly fine in localhost: https://i.sstatic.net/JGy2g.png I sus ...

Interacting with a JavaScript alert by clicking the OK button using C# in a web browser control

In my C# Windows Forms program, I am utilizing a webbrowser control to navigate multiple pages of a website and interact with forms to carry out transactions. I initially tried using httpwebrequest and webclient, but encountered challenges with cookies and ...

The second parameter of the filter function is malfunctioning

I'm currently delving into the "filter" function in AngularJS. Upon reviewing the documentation, I've discovered that it can also take a second parameter. When set to "true", it carries out a strict comparison. HTML <fieldset> <leg ...

Monaco Editor: Module 'monaco-editor' is missing despite being successfully installed

During the development of my desktop application with electron, I encountered an issue with installing Monaco Editor. After using npm install monaco-editor, running the application resulted in a message saying Cannot find module 'monaco-editor'. ...

How can the camera's yaw be accurately determined using THREE.js techniques?

Is there a way to calculate the 2D representation of an object's rotation (yaw) in a 3D scene using built-in methods in THREE.js? While I currently have this functionality working with the help of the solution provided at How to derive "standard ...

What is the process for altering the background color in this code snippet?

I'm looking to customize this button by changing the background color to a dark red. Additionally, I want the text to transform when hovering over the button to say G.F.Y.T.S. Here is the code snippet of what I have attempted so far: <input type= ...

Execute the SQL "function" (or stored procedure?) whenever a database column is queried

Running on MySQL 5.6, I encounter a situation where various "name" columns in the database lack formatting and sanitization upon importation through CSV data dumps by customers each year. This results in names such as Phil Eaton, PHIL EATON, Phil EATON bei ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

The HTML file contains the complete version number of Firefox

If you're an expert in HTML, take a look at my expandable start page. I know there's room for improvement, and I'm seeking advice on automatically updating the Firefox browser version number in line 106 of the code snippet below. (Linux Mint ...

Looking to fill every space? Try using React with MUI Grid!

I am currently using Material UI Grid to create an image grid, and I am facing challenges in eliminating the gaps between certain grid items. Despite attempting to modify the alignitems and justify values of the container, I have not been successful in r ...

Exploring the realms of Dynamic Programming to retrieve comprehensive match data

I have developed a basic dynamic program that can retrieve the first matched data. However, I now aim to extract all matched data from my dataset: let countryList = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka ...

Utilize Firestore's limit feature with variables

Is it possible to utilize a variable (page) in the limit parameter within Firebase Firestore while using Vue? export default { data() { return { page: 1, } }, methods: { }, firestore: { Words: db.collection("Words").w ...

Looking to connect a dropdown to an icon that has the type "button"?

I am facing a challenge with an icon placed on a Twitter Bootstrap container. My goal is to click on this icon and have a dropdown menu appear, offering various options that link to different websites. Currently, I am able to display the dropdown menu, but ...

Combining shapes in three.js

I've encountered a scenario where my scene consists of multiple meshes, each with different shapes and sizes. By looping through each mesh and utilizing geometry.merge(), I successfully created a new mesh from the geometries in the scene. The challe ...

AngularJS: steer clear of relying on the 'angular' global variable

Is it advisable to refrain from using the 'angular' global object within Controllers, Services, etc? Suppose we want to call the function: angular.isDefined(myVar) How should we reference the 'angular' object? Possible approaches: ...

Tips for altering the smoke hue on a three.js panel

Click here Seeking help with threejs and HTML canvas. The fiddle showcases black smoke - how can I change it to white or gray? Even after trying a PNG image of blue smoke, the rendering remains black. It's puzzling where the black color is originati ...

Sending parameters and obtaining results with AngularJS

I'm encountering an issue. I need to trigger a function with arguments and receive results upon clicking on a .md-button with ng-click. Here's the HTML: <md-button class="md-raised md-primary" ng-click="setreg.register({{reg.email}},{{reg.pa ...