Table of Contents
Content Overview
1 Our goal
2 Installation of Laravel and Vue JS
3 Vue Router and file structure
4 SPA Implementation
Home Web Front-end Vue.js How to implement single page application (SPA) with Laravel8+Vuejs

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

Jul 25, 2022 pm 07:34 PM
vue laravel

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
Copy after login

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

composer require laravel/ui
Copy after login

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
Copy after login

Don’t forget to compile Vue when changes occur.

npm install && npm run dev
Copy after login

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
Copy after login

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;
Copy after login

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
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。
Copy after login

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>
Copy after login

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)
});
Copy after login

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', '.*');
Copy after login

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

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


    <meta>
    <meta>

    <title>Laravel</title>

    <link>




    <div></div>

    <script></script>


Copy after login

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

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

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

npm run dev
Copy after login

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

React, Vue, and the Future of Netflix's Frontend React, Vue, and the Future of Netflix's Frontend Apr 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.

How to implement component jump for vue How to implement component jump for vue Apr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and &lt;router-view&gt; components to perform hyperlink jump, and specify the :to attribute as the target path. Use the &lt;router-view&gt; component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

See all articles