What is the best approach to structuring Vue.js components in conjunction with a Laravel backend?

A template for the main site page has been created:

https://i.sstatic.net/tB3QC.jpg

The main site page contains multiple sliders. Each slider will be a vue.js component that makes a request to the server to retrieve JSON data using the Post method. I plan to include numerous methods in my IndexPageController for this purpose. Additionally, each slider will need its own Resource. Is this approach correct?

Answer №1

Instead of creating multiple slider components for each section in your template, consider creating a single slider component and passing it the data source as a prop. You can then use Axios or VueResource to fetch data from that source. Here's an example:

//test.blade.php

<div id="app">
    <slider-component :source="{{$source}}"></slider-component>
</div>

//$source is a variable passed to the blade view, representing the endpoint to fetch data from

Here's how you can fetch data in your slider component:

//slider component
<template>
    //your html goes here
</template>

<script>
    export default {
        props : ['source'],
        data(){
            return {
                items : [],
            }
        },
        created(){
            axios.post(this.source , {
                 //request body
            })
            .then(res => {
                //handle the request and assign items the response body
            })
            .catch(err => {
                //error handling
            });
        }
    }
</script>

This way, you have a customizable slider component that can fetch data from any source.

In Laravel, create endpoints in routes/web.php like this:

//routes/web.php
Route::get('/products/hot-deals" , "ProductController@hotDeals");

And in the Product Controller:

use App\Models\Product;

class ProductController extends Controller {

    public function hotDeals(){
        //query your product model to select the hot-deals items
        return Product::where('price' , '<=' , 100);
    }
}

Hope this helps, good luck!

Answer №2

The ideal scenario is for a component to be an independent entity that does not interfere with other components outside of it. You can make resource requests from a component without concerning any other Vue.js components. Additionally, you can customize actions within a component without affecting others. The possibilities are endless when working inside a component.

To handle complex structures, consider creating child components which can further contain additional children components and so forth.

Server request logic can be placed in either the created or mounted hooks. Since requests are asynchronous, ensure your component receives all data before proceeding. Display a loader on your element while waiting for data retrieval. When the data is retrieved, proceed accordingly.

Incorporate the slider as a whole component based on the image provided, where each card within the slider is also a separate component. Utilize v-for on the card component to dynamically generate multiple cards. Furthermore, include other components within the card component to streamline your logic. Opting for a single file Vue component (.vue file) can significantly enhance your workflow.

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

Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well. After ex ...

difficulty encountered with page.registerstartupscript function

I've been using page.registerstartupscript in my C# code behind. Here's an example: string item1="category1"; string Script = "window.program = '" + item1 + "';"; Page.RegisterStartupScript("PopupScript", Script); The variable ite ...

What is the process for including echo HTML field in the WooCommerce order view?

I have successfully added HTML input fields within functions.php. However, these echoed fields are not displaying in WooCommerce orders after placing an order. I am looking for a way to include the values and labels of these fields in the orders view wit ...

Error encountered while attempting to display a view when pressing TouchableOpacity in a React Native application

Having trouble rendering a view when pressing on a TouchableOpacity in my React Native app. Any suggestions for a solution? import React, { Component } from 'react'; import { AppRegistry, View, TouchableOpacity } from 'react-nati ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Utilizing JavaScript and jQuery to dynamically update text within a div element with the click of a button

Here is an example of working with arrays: const arrayExample = [ 'First element in the array', 'Second element, simply put', 'Impressed by the third one' ]; Trying various methods... $("#clickMeButton").click(function ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

"Is there a way to reverse the action of $( "button" ).remove()

Currently, I have implemented JQuery's $( ".button" ).remove(); function to get rid of all the buttons on my webpage immediately after a user clicks the print PDF button that changes the HTML page into a PDF. Nevertheless, once this process is done ...

Blocking server.js in node.js can be achieved by modifying the code to prevent

Challenge Description In my server.js file, I have included a config file. This is how my server.js file looks: Includes some necessary imports Requires config.js -> makes an API call to get the configuration data using promises Starts the ser ...

Activating an event in jQuery when removing content in the ACE editor

I have integrated the Ace editor into my website and it has been working smoothly so far. My requirement is to capture every text change that occurs within the editor. I have assigned the id "Ace_javascript_editor" to the editor. However, when I try to use ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

Using V-for to display several elements at once

Embarking on my Vue.js journey, so please go easy on me! :smiley: I've encountered an issue where binding elements separately on two columns is causing layout havoc. All images load in the first row with articles appearing below. the code => < ...

Guide on generating a nested JSON format from a specified table structure in Laravel

How can I retrieve data from the given table structure in the JSON format using Eloquent ORM? Table structure: authors id - integer name - string posts id - integer author_id - integer title - string images id - integer post_ ...

Are top-level script blocks being executed multiple times?

I am perplexed by the strange behavior I am experiencing with my ASP.Net website. In the rendered HTML, a script block is causing an alert that should run once to actually run twice. It seems like there are two separate threads running the same code in Chr ...

Differentiating between the simple and luxurious text editing features available in the TinyMce editor

I am currently utilizing the TinyMCE editor to enhance the appearance of a textarea field where users can input comments. My goal is to offer two options for users: one for plain text and the other for a rich text editing experience. When a user selects th ...

Why doesn't the 'javascript' named directory have access to my localhost?

My Ubuntu 16.04 system is running Apache 2.4.18. Recently, I created a directory called "javascript" within /var/www/html and added an HTML file to it. However, when attempting to access the file via localhost/javascript/, I received the following error me ...

In JavaScript, we have an array of objects where each object contains both another array and an integer value

I'm feeling a bit lost on how to tackle this issue and could use some guidance. I've been struggling to find resources on how to load an array that is nested within an Object. The following function is where I've hit a roadblock: function F ...

Struggling to achieve consistent heights for elements in Vue 3 with TypeScript and Quasar, encountering intermittent success

In my current Vue 3 / TypeScript / Quasar project, I have been exploring ways to ensure that all elements marked with the class .plan-item share the same height. After delving into this challenge, I came up with the following code snippet: const equalizeH ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...