Home  >  Article  >  Web Front-end  >  How to implement single page application (SPA) with Laravel8+Vuejs

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

青灯夜游
青灯夜游forward
2022-07-25 19:34:192346browse

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.com. If there is any infringement, please contact admin@php.cn delete