vant4 多个单页面路由

1.Vue 组件#

为每个 SPA 创建 Vue 组件。将它们放在 resources/js/components 目录中。

Spa1Component.vue:

<template>
  <div>
    <h1>SPA 1</h1>
    <!-- SPA 1 Content Here -->
  </div>
</template>

<script>
export default {
  // SPA 1 Script
};
</script>

Spa2Component.vue:

<template>
  <div>
    <h1>SPA 2</h1>
    <!-- SPA 2 Content Here -->
  </div>
</template>

<script>
export default {
  // SPA 2 Script
};
</script>

2. 主要 JavaScript 文件#

在 中 resources/js/app.js,根据数据属性动态导入组件。

import { createApp } from 'vue';

document.addEventListener('DOMContentLoaded', () => {
  const appDiv = document.getElementById('app');
  const componentName = appDiv.dataset.component;

  import(`./components/${componentName}.vue`).then((module) => {
    createApp(module.default).mount('#app');
  });
});

3. 刀片模板#

创建一个将动态加载不同组件的 Blade 模板。

资源 / 视图 /app.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SPA</title>
</head>
<body>
    <div id="app" data-component="{{ $componentName }}"></div>
    @vite('resources/js/app.js')
</body>
</html>

4. Laravel 路线#

设置路由以 routes/web.php 将适当的组件名称传递给视图。

use Illuminate\Support\Facades\Route;

Route::get('/spa1', function () {
    return view('app', ['componentName' => 'Spa1Component']);
});

Route::get('/spa2', function () {
    return view('app', ['componentName' => 'Spa2Component']);
});

此设置允许您维护单个入口点 ( app.js),同时根据路由动态加载不同的组件,从而使多个 SPA 的管理更简单、更集中。

本作品采用《CC 协议》,转载必须注明作者和本文链接
写代码是一件趣事。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。