search
HomeWeb Front-endVue.jsHow to implement single page application (SPA) with Laravel8+Vuejs

Laravel8 How to implement single-page application with Vuejs? The following article introduces how to implement a single page application (SPA) with Laravel 8 and Vuejs. I hope it will be helpful to everyone!

How to implement single page application (SPA) with Laravel8+Vuejs

We all know that Laravel is a great framework! It allows full-stack engineers to build front-end and back-end websites in one stop. As a result, we can quickly build and deliver high-quality and secure web projects. But its power doesn't stop there. There is so much more to explore and discover in Laravel. For example, we have written a series of Vue JS components that can be embedded into Laravel pages to dynamically provide UI interactions for users. Interesting, right? But next we need to explore is, is it possible to build a single page application (SPA) in a Laravel project? Of course, why not!

Before everything starts, we first need to know why our project needs SPA? It is undeniable that SPA gives users a better experience. It makes pages load faster without reloading, allowing users to access the website even if they don’t have an internet connection! The examples go on and on. Of course, this will also bring some disadvantages, so you still need to think twice before using it. Whether you are building an SPA or MPA (Multiple Page Application), make sure it meets your needs. But Laravel lets us build a MAP project by default, doesn't it? So I thought it was time for us to explore how to build a SPA in a Laravel project. Officially set off!

Content Overview

  • Our goal
  • Laravel and Vue JS installation
  • Vue Router and file structure
  • SPA implementation

1 Our goal

What do we need to build at the end of this article? Quite simply, we're going to have a SPA with two pages inside. If we click on another page, it won't reload. Take a look at the final result of the project below.

How to implement single page application (SPA) with Laravel8+Vuejs

2 Installation of Laravel and Vue JS

We will use the new Laravel as a starting point. Usually we can create a new project through the following command:

composer create-project laravel/laravel --prefer-dist laravel-vue-spa

Creation completed, you already have a new project. Then you need to install Vue JS in it.

composer require laravel/ui

The last thing that needs to be done is to integrate Vue JS into the Laravel project. Thank God, we can use the following command to help us integrate. Very simple.

php artisan ui vue

Don’t forget to compile Vue when changes occur.

npm install && npm run dev

3 Vue Router and file structure

Because in SPA, users can navigate to the page they want to reach through routing. So you need to install an additional library, Vue Router.

npm install vue-router

The most important step before implementing SPA is the file structure. Create new folders and files in the resources/js directory. The code structure is as shown in the figure below.

How to implement single page application (SPA) with Laravel8+Vuejs

Under the resources/js directory, you need to create a new directory named layouts, and pages Table of contents. layouts The content contained in the directory is as you think, and is used to display the layout files of the pages in the pages directory. Confused? This will make the structure of the SPA clearer later in the process of implementing it.

Don’t forget to create the router.js file to store all the routes we need.

4 SPA Implementation

It’s time to implement SPA! First, modify the router.js file (in resources/js/router.js)

import Vue from 'vue';
import VueRouter from 'vue-router';

import Home from './pages/Home.vue';
import About from './pages/About.vue';

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    linkExactActiveClass: 'active',
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/about',
            name: 'about',
            component: About
        },
    ]
});

export default router;

on the fourth and fifth lines, we need to be here Configure two pages, homepage and about page. I know that these two pages don't exist yet. We will create them later. On lines 9-24 we register all the routing information we need. Therefore each route object has path, name and component properties for rendering/display.

The routing has been prepared, what should we do now? We will display these pages in a layout file. Remember App.vue already in the layouts directory? Let’s create it.

<template>
  <div>
    <nav>
      <router-link>Laravel-Vue SPA</router-link>      >
      <button>
        <span></span>
      </button>
      <div>
        <ul>
          <li>
            <router-link>
              Home
            </router-link>
          </li>

          <li>
            <router-link>
              About
            </router-link>
          </li>
        </ul>
      </div>
    </nav>

    <div>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  watch: {
    $route() {
      $("#navbarCollapse").collapse("hide");
    },
  },
};
</script>

————————————————
原文作者:wj2015
转自链接:https://learnku.com/vuejs/t/54399
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

Note lines 17-23, where the \ tag is used. This routing link is similar to the \ tag and is used to navigate between multiple pages. So the question is, where will the page be rendered? Look at the \ tags on line 40, so the page will be rendered at the \ tags.

Okay, the home page and about page have not been created yet. Open the Home.vue page in the pages directory.

<template>
  <div>
    <div>
      <div>
        <div>
          <div>About</div>

          <div>About Page</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {

}
</script>

Until this step, we have set the routing for jumps between SPA pages and the layout of the display page. The last thing we need to do is to modify the entry file of Vue JS.

Open resource/js/app.js and modify it.

/**
 * 首先,我们将重载项目中所有包含 Vue 或其他库的 JavaScript 依赖
 * 使用 Vue 和 Laravel 构建健壮、强大的 web 应用,这是个很好的开始。
 */

require('./bootstrap');

window.Vue = require('vue').default;

import router from './router';
import App from './layouts/App.vue';

/**
 * 如下代码块可用于自动注册 Vue 组件。这将递归的扫描 Vue 组件目录
 * 并按照其 "文件名" 自动注册。
 *
 * 比如 . ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * 随后,我们将创建一个新的 Vue 应用实例并将其挂载到页面。
 * 然后,你可以附加组件到应用中或自定义 JavaScript 脚手架以满足特殊需求。
 */

const app = new Vue({
    router,
    el: '#app',
    render: h => h(App)
});

On lines 11 and 12, the layout file and routing file are introduced. On line 34, Vue is told to use routing and on line 36, rendering is specified to the specified layout.

万事俱备,是时候告诉 Laravel 通过 Vuejs 实现 SPA 了。打开 routes/web.php 并在此创建其他入口。

<?php use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web 路由
|--------------------------------------------------------------------------
|
| 这里是注册应用 web 路由的地方。这些路由将会被 RouteServiceProvider 加载
| 也就是那些包含了 "web" 中间件的路由组会加载这些路由。
| 现在继续创建一些有意思的东西!
|
*/

Route::get(&#39;/{any}&#39;, function () {
    return view(&#39;layouts.vue&#39;);
})->where('any', '.*');

在如上代码中,我们告诉 Laravel 用户所有访问都将返回 resources/views/layouts/vue.blade.php 文件。很明显,我们还没有这个文件,一起创建下。

nbsp;html>
getLocale()) }}">


    <meta>
    <meta>

    <title>Laravel</title>

    <link>




    <div></div>

    <script></script>


好了,这里有两个重点。第一个重点,在 16 行,创建了一个 id 为 “app” 的

标签。为何这很重要呢?因为 Vue 只能渲染到标致 id 为 “app” 的 div(或其他标签)上。如果你还记得 resources/js/app.js 的 35 行,我们告诉 Vue ,渲染到 id 为 “app” 的标签上。第二个重点是在 18 行,我们引入了编译后的 Vue JS 文件。

就先这样了。在你去测试前,请确保编译了 Vue JS 脚本:

npm run dev

然后运行服务并在浏览器中打开。

How to implement single page application (SPA) with Laravel8+Vuejs

这!我们成功在 Laravel 中构建了 SPA!如果你从一个页面导航至另一个页面,将不会引发页面重载。

在本文完结前,我再说一点点,我们可以把 MPA 和 SPA 构建到一起。比如 SPA 页面只用于关于页。你需要为 SPA 添加一个端点 /about/{any} ,然后其他端点依旧是 MPA。或者哪怕项目中有多个 SPA 。通过 Laravel,也可以轻易的把其他 SPA 或者 MPA 或把他们一起构建到一个项目中!这不是就很赞吗!

是时候借宿了。在最后,我想说 Laravel 是一个非常棒的框架。你探索的越多,越能体验到它的强大。感谢您的阅读,我们下次见。

【相关视频教程推荐:vuejs入门教程web前端入门

The above is the detailed content of How to implement single page application (SPA) with Laravel8+Vuejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool