Passing Data to a Different Route in Vue.js

Being new to Vue.js, I have a question on how to efficiently handle data retrieval from my backend application. Here is the code snippet that fetches all the data:

var app2 = new Vue({
    delimiters: ['%%', '%%'],
    el: '#app2',

    data: {
        articles: []
    },

    mounted : function()
    {
        this.loadData();
    },

    methods: {
        loadData: function() {
            this.$http.get('/backend/FpArticle/articleApi').then(response => {
                // get body data
                this.articles = response.body;
            }, response => {
                // error callback
            });
        },

    },

The above code seems straightforward enough. Now, to display the retrieved data in a table view on the frontend, I use the following code:

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
</tr>

This method works well. However, I want to implement an edit feature where users can modify certain data elements of an article. My initial thought process for achieving this is as follows:

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
  <td><a href="/article/{{ article.id }}">edit</a></td>
</tr>

To implement this functionality, I believe I need another component that will take the article id, retrieve the corresponding data, display it in a form, and handle the save event. While I have some ideas on how to handle the latter part, I am unsure about how to approach routing with a new component in Vue.js. I was considering something like this:

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
  <td><button v-on:click="editArticle(article.id)">edit</button></td>
</tr>

If anyone has any helpful tips or recommendations on the best way to achieve this functionality, I would greatly appreciate it! Thank you!

Answer №1

Absolutely, you're heading in the right direction. Utilizing VueRouter is key. It's essential to set up routes with your components like this:

const router = new VueRouter({
  routes: [
    { path: '/articles', component: ArticlesList },
    { path: '/articles/:id', component: Article }
  ]
})

Subsequently, you can navigate to your Article view with <router-link> (which will be displayed as an <a> tag by default):

<td><router-link to="'/article/' + article.id">edit</router-link></td>

Furthermore, don't forget to include the

<router-view></router-view>
tag to render your component's view. The component that matches the route will be displayed here.

All the details are available in the documentation ;-) https://router.vuejs.org/en/essentials/getting-started.html

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

Click event in safari failing to trigger on iPhone

Issue with click event on mobile Safari browser when using an iPhone In a React class component, the click event listener is triggered on the window when opening the menu. This functionality works correctly everywhere except for iPhone Safari. toggleMenu ...

Learning about a basic sorting algorithm that analyzes and compares different values

While on the hunt for a simple jQuery sorting script, I stumbled upon this gem online: $(function() { $('ol').each(function() { var matches = $('li', this).filter(function() { // Each item var text = $(this).te ...

Load a page from a different domain using uframe

Looking for a solution to successfully load an external URI using uFrame. Currently encountering an "Access Denied" issue when attempting to do so on Firefox. Any suggestions? ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

Utilize an API call to fetch data and seamlessly showcase it on the webpage using Vue.js

I have created an API and defined it in my TypeScript file const Book = { async getBookType(intID: string): Promise<Book[]> { // const intId = API.Product.getCurrentId(); const intId = ''; const response = await h ...

What is the best way to sequentially read various sections of a file in vue.js?

I am currently working on a browser tool that analyzes a large file and provides statistics based on its content. The tool randomly selects k parts of the file for processing, treating each part individually. As each part is processed, an object is update ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

Struggling to navigate web pages with Selenium using Java is proving to be a challenge

I am currently working on using Selenium's HtmlUnitDriver and WebElement classes in Java to automate clicking the "Download as CSV" button on Google Trends. The issue that I am encountering is that the button remains hidden until another settings men ...

What steps should I take to execute a task during input checkout?

Check out my code below: $(document).on('checkout', 'input', function(){ alert('input is not focused anymore'); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <i ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

Locate every item that has a value that is not defined

My data is stored in indexeddb, with an index on a text property of the objects. I am trying to retrieve all objects where this property's value is undefined. I have been experimenting with IDBKeyRange.only(key), but when I use null, undefined, or an ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

What is the best way to ensure that JavaScript is loaded in a specific sequential order?

I'm having trouble ensuring that JS files load in the correct sequence, despite my efforts to research async and defer on various platforms. This is the structure of my code: <script src="lang.js"></script> <!--loading either ...

Substituting placeholders within a docx template remains incomplete

Utilizing this specific library, I am implementing a feature to substitute placeholders within a docx template and generate multiple documents. The technologies involved are neutralino and vue for the front-end, where I have devised a method that transmits ...

Having trouble reaching the AngularJS animation class breakpoint for removeClass or addClass operations

Can anyone help me figure out why my animation class isn't triggering in this codepen? I can access the controller methods fine, but the animation class doesn't seem to work properly. Any ideas on what I might be missing? Check out the codepen w ...

Tips for interacting with a modal using Bootstrap Vue

I have implemented a sophisticated modal in its own component. It operates on a duplicate of the supplied model to enable the user to cancel the action. <template> <b-modal v-if="itemCopy" v-model="shown" @cancel="$emit('input& ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Check the input in the text box against the selected options to validate it

Currently, I am working on an add contacts page where I am facing the challenge of displaying an error message or highlighting input as invalid if a user tries to enter a contact name that already exists. It seems like one solution could be populating a s ...

Having difficulty choosing a drop-down menu option with AJAX technology

My current project involves creating a page where the database is updated upon a drag-and-drop event. Specifically, I have implemented drag-and-drop functionality on a page, and whenever a div (deal-card) is dragged and dropped into another div (stage-colu ...