How to create a JSON value passing link in VueJS

I have an existing VueJS template file (let's refer to it as Template A) that contains a table populated with data from a JSON output.

Example of JSON output:

{"driver_id":1,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"13","driver_trailer":"83","driver_status":"driving","has_violations":false},
{"driver_id":2,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"58","driver_trailer":"37","driver_status":"sleeping","has_violations":true},
{"driver_id":3,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"80","driver_trailer":"27","driver_status":"driving","has_violations":true},

Below is an image showing how the table appears:

https://i.sstatic.net/b9oR0.png

The button in the table is conditionally displayed when has_violations is true. Here is the code for the button:

<template slot="list_of_violations" slot-scope="row">
<b-button v-if="row.value.list_of_violations == true" id="account_list">View Account List</b-button></template>

What I am trying to achieve is making this button a link to another VueJS template file (referred to as Template B), where it will take the driver_id from Template A and perform the following actions:

  1. Send an AJAX request to retrieve all current violations related to the driver_id (from Template A) to the backend application
  2. Process the Ajax response
  3. Display the Ajax results in a table within Template B

My challenge lies in establishing the connection between these two templates and transferring the driver_id from Template A to Template B.

Is this considered state management? Or perhaps nested routing? I find myself quite perplexed by this situation.

Answer №1

Have you considered using props (properties)? Here's an example tailored to your needs:

<template-b driver-id="{{ driver_id }}"></template-b>

You can utilize the driver-id prop within Template B:

// Adapted snippet based on VueJS documentation
Vue.component('template-b', {
    // Accepting the 'driver-id' property
    props: ['driverId'], // JavaScript uses camelCase for props
    template: 'Display results for {{ driverId }}'
});

In template B, you have the option to retrieve data from the server using AJAX. This data can then be stored and accessed within template B.

The decision of when and where to display template B is entirely yours. One approach could involve storing the driver_id of the clicked row as part of the state in template A. Subsequently, validate if that driver_id holds a value before showing template B:

<template-b v-if="driver_id" driver-id="{{ driver_id }}"></template-b>

The driver_id is sourced from the state of template A. Whenever a button in another row is clicked, simply update the driver_id within the state, causing template B to refresh automatically. Consider implementing a watcher for the driver_id prop in template B.

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

Replace a function within a placeholder

Looking to validate the functionality of my custom Google Maps geocoder directive. In my code, I've set up a geocode constructor that I have already partially implemented: ... link: function(scope) { var map, geocoder, myLatLng, ...

Is there a state leakage issue with karma, jasmine, and browserify?

I have encountered a puzzling problem with my two karma tests for Vue.js. Individually, they pass successfully, but when executed as part of a suite, one of them fails unexpectedly. Although I am relatively new to JS testing, I suspect that there might be ...

Executing PHP Code with an External JavaScript File in an HTML Document

I have a script called initialize_database.js that utilizes JQuery to trigger a PHP script for creating a database and some tables. I made sure the PHP script is working correctly by adding HTML to test it independently, and it performed as expected. Below ...

What is the recommended approach for unchecking the last element in ngRepeat Check-Boxes with AngularJS?

I have implemented the Check-box model with AngularJS, following the guidelines provided at . Now I need to make sure that for certain sets of checkboxes, the last checkbox should uncheck all others when clicked. Can someone guide me on how to add an ngC ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functio ...

Enhancing Material UI KeyboardDatePicker with personalized CSS design

Material UI KeyboardDatePicker is the component I'm currently using. https://i.sstatic.net/It50L.png In order to remove the black line visible in the datepicker (as shown in the screenshot), what steps should I take? Displayed below is the code ...

Reducer incorporating nested array mappings

Struggling with a complex redux situation that involves two objects, Track and Target interface Track { id: number, ...other fields } interface Target { id: number (same as the Track) tracks: Track[] ...other fields } The goal is to fetch track ...

Attempting to link the hover action of an image to emphasize a text link situated beneath it within a javascript document

I have been approached to assist with updating an older website that was formerly in Flash and is now being archived for portfolio purposes. I have successfully completed all the tasks except one, as my expertise in javascript is limited. The webpage is d ...

I can't seem to figure out why I keep encountering a runtime error whenever I attempt to create a basic route in the latest version of nextjs, version 13.5

Encountering an error while attempting to create a basic route in app/dashboard/page.tsx. The error message suggests that the contents are not a valid react component, even though they conform to valid react component syntax. Unhandled Runtime Error Erro ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

Using ES6 template strings to access MongoDB object keys

I am attempting to modify an array within my collection using the following method: var str = "list.0.arr"; db.collection('connect').update({_id: id}, {$push: { `${str}`: item}}); While the above code works perfectly fine, it throws an er ...

Utilizing Various Styles within a single Google Sheets Cell

In Cell A1, I have a challenge where I need to merge 4 different arrays of names, separated by commas. Each name should have its own styling based on the array it belongs to - red for array1, green for array2, orange for array3, and gray with a strike-th ...

Encountering a problem while trying to pin a message on Discord

Whenever a message is pinned in discord, it causes the bot to crash with the following error (although it can recover with forever but that's beside the point). The pinned message can be of any type (regular or embed). if (!value) throw new RangeE ...

How to showcase elements[i] from an array using React

I need to cycle through an array of objects and display each item in a component, with the prop being the index number of the array item. This is the snippet of code I have: import React from 'react'; import './projecten.scss'; import ...

Is it possible to register multiple handlers for a single event in socket.io?

When it comes to explaining how to handle receiving events, the documentation for socket.io doesn't specify if multiple event handlers can be used for the same event. For instance, if I have two components that both need to handle the event io.on(&apo ...

The code executes successfully when run locally with console logging, however, it encounters issues when run

As a newcomer to the project development world, I'm navigating my way through unfamiliar territory. Currently, I'm utilizing an npm module called mal-scraper to extract data (show titles, anime links, and images) from the MyAnimeList website. My ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

I am interested in invoking a function from a different component

I am facing an issue with my component AddPost.js where I am trying to use a method from machine.js. However, when I attempt to import AddPost into the machine.js file, it throws an error: Possible Unhandled Promise Rejection (id: 0): ReferenceError: addIn ...

jQuery equivalent of this script

My HTML code triggers a JavaScript function when the input is changed: <input type="file" id="file-uploaded" onchange="checkinput(this);"> The script checks if the input actually contains a file: function checkinput(input) { if (input.files &a ...