创建vue多页面项目

首先创建一个vue项目,不懂得可以看
页面创建vue项目
或者
npm创建vue项目

第一步:修改配置vue.config.js

创建成功后的项目配置为

/**
 * 简单页面使用配置
 */
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false
})

将其修改为如下两段代码之一
主要目的是为了能够扫描到pages包下的html

const { defineConfig } = require( '@vue/cli-service' )
let glob = require('glob')
//配置pages多页面获取当前文件夹下的html和js
function getEntry(globPath) {
        let entries = {}, tmp, htmls = {};
        // 读取src/pages/**/底下所有的html文件
       glob.sync(globPath+'html').forEach(function(entry) {
              tmp = entry.split('/').splice(-3);
             htmls[tmp[1]] = entry
            
        })
        
       // 读取src/pages/**/底下所有的js文件
       glob.sync(globPath+'js').forEach(function(entry) {
            tmp = entry.split('/').splice(-3);
            //if(tmp[1] == "login"){
                entries[tmp[1]] = {
                entry,
                template: htmls[tmp[1]] ? htmls[tmp[1]] : 'index.html', //  当前目录没有有html则以共用的public/index.html作为模板
                filename:tmp[1] + '.html'   //  以文件夹名称.html作为访问地址
           //}
           
        };
    });
    console.log("me")
    console.log(entries)
    return entries;
}
let pages = getEntry('./src/pages/**/*.');// 

module.exports = defineConfig( {
    // transpileDependencies: true,
    //filenameHashing: false,
    lintOnSave:false,
    pages,
    //outputDir: "../seckill/src/main/resources/static/assets", //将build的文件,存放到某个目录
    publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
} )

或者为

const { defineConfig } = require( '@vue/cli-service' )
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')

const path = require( 'path' )
const fs = require( 'fs' )
// const CopyWebpackPlugin = require('copy-webpack-plugin')
const {
    argv
} = require( 'process' )

const resolve = dir => path.resolve( __dirname, dir )

const isModuleServe = argv.findIndex( item => ( item === 'server:module' || item === 'build:module' ) ) !== -1;
const whiteModuleList = [ 'index' ]

const config = {
    entry: 'main.js',
    html: 'index.html',
    pagesRoot: resolve( 'src/pages' )
}

const getSubSystem = ( ) => {
    const allSubSystem = [ ]
    const findAllSubSystem = ( source, allSubSystem ) => {
        const files = fs.readdirSync( source )
        for ( let i = 0; i < files.length; i++ ) {
            const filename = files[ i ]
            const fullname = path.join( source, filename )
            const stats = fs.statSync( source, filename )
            if ( !stats.isDirectory( ) ) continue
            if ( fs.existsSync( `${fullname}/${config.entry}` ) ) {
                /* 是否存在模块化 */
                if ( isModuleServe ) {
                    const pass = argv.find( item => item === filename ) !== undefined || whiteModuleList.indexOf( filename ) !== -1
                    /* 不在白名单且没有自定义打包的模块直接跳过, 结束本次for循环 */
                    /* indexOf为了去重,防止同一模块二次打包 */
                    if ( !pass || ( allSubSystem.length > 0 && allSubSystem.indexOf( filename ) !== -1 ) ) continue;
                    allSubSystem.push( fullname )
                } else {
                    allSubSystem.push( fullname )
                }
            }
        }
    }
    findAllSubSystem( config.pagesRoot, allSubSystem )
    console.log( allSubSystem )
    return allSubSystem
}

const getPages = ( ) => {
    const pages = {}
    getSubSystem( )
    .forEach( page => {
        console.log("me")
        
        const filename = page.slice( config.pagesRoot.length + 1 )
        pages[ filename ] = {
            entry: `${page}/${config.entry}`,//'E:\\workspaces\\store\\my-store\\seckill_ui-pageEnd_1\\src\\pages\\test/main.js',//
            template: `${page}/${config.html}`,
            filename: filename === 'index' ? config.html : `${filename}/${config.html}`
        }
        console.log(pages)
    } )
    return pages
}
const pages = getPages( )

module.exports = defineConfig( {
    // transpileDependencies: true,
    //filenameHashing: false,
    lintOnSave:false,
    pages,
    //outputDir: "../seckill/src/main/resources/static/assets",
    publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
    devServer: {
        proxy: 'http://localhost:58080'
    },
} )

第二步,创建页面

目录结构为

在这里插入图片描述

2.1 main.js
main.js是pages下自己创建的包下的
需要什么就就导入什么,和最外层的main.js用法一样

引入Login.vue,将其在index.html中显示

import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import Loginfrom './Login.vue'
import router from '@/router'

import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'

import iView from 'iview';
import 'iview/dist/styles/iview.css'; 


Vue.use(VXETable)
Vue.use(iView);
Vue.use(ElementUI);

import CollapseTransition from 'element-ui/lib/transitions/collapse-transition';
Vue.component(CollapseTransition.name, CollapseTransition)



// <font-awesome-icon icon="fa-solid fa-plus" />新增</Button>
import { library } from '@fortawesome/fontawesome-svg-core'
import { fas } from '@fortawesome/free-solid-svg-icons'
import { far } from '@fortawesome/free-regular-svg-icons'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { FontAwesomeIcon, FontAwesomeLayers, FontAwesomeLayersText }
 from '@fortawesome/vue-fontawesome'
 
library.add(fas, far, fab)
 
Vue.component('font-awesome-icon', FontAwesomeIcon)
Vue.component('font-awesome-layers', FontAwesomeLayers)
Vue.component('font-awesome-layers-text', FontAwesomeLayersText)
/** */

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(Login)
}).$mount('#app')

2.2 index.html
其中main.js中的#app就是html中的id=“app”

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="loginport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

2.3 路由跳转
当跳转时

this.$router.push({path:'/dep'})

一定要加上一个占位符,不然跳转以后无法显示页面

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

2.4.其中main.js和index.html必不可少
因为你有几个html在build之后就有几个html
2.5.这样的目录结构,在npm run serve运行vue项目以后,请求路径为你的包名,如:请求上图中的login项目,那么我的请求路径则为localhost:8080/login,下面两张图是启动项目效果图

在这里插入图片描述
在这里插入图片描述
2.6

outputDir: "../seckill/src/main/resources/static/assets/module-js",

publicPath: process.env.NODE_ENV === 'production' ?
        '/dddd/assets/module-js/' : '/', // /material/assets/module-js

 proxy: 'http://localhost:58080' //和spring启动的端口一致

在这里插入图片描述在这里插入图片描述

3将build后的文件进行使用

3.1 写页面
在这里插入图片描述
在Login,vue中写入

<template>
    <div id="app">
        测试vue多页面使用
    </div>
</template>

进行访问
/后面时包名
在这里插入图片描述成功

3.2进行build操作
执行npm run build

Microsoft Windows [Version 10.0.17763.2686]
(c) 2018 Microsoft Corporation. 著作權所有,並保留一切權利。

E:\workspaces\store\my-store\seckill_ui-structure>npm run build

> views@0.1.0 build
> vue-cli-service build

me
{
  dept: {
    entry: './src/pages/dept/main.js',
    template: './src/pages/dept/index.html',
    filename: 'dept.html'
  },
  login: {
    entry: './src/pages/login/main.js',
    template: './src/pages/login/index.html',
    filename: 'login.html'
  },
  'seckill-dept': {
    entry: './src/pages/seckill-dept/main.js',
    template: './src/pages/seckill-dept/index.html',
    filename: 'seckill-dept.html'
  },
  test: {
    entry: './src/pages/test/main.js',
    template: './src/pages/test/index.html',
    filename: 'test.html'
  }
}

-  Building legacy bundle for production...

 WARNING  Compiled with 3 warnings                                                                           下午4:21:38

 warning

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  img/ionicons.6e8059e8.svg (542 KiB)
  img/login-background.6f6c293d.jpg (509 KiB)
  css/chunk-vendors.ba1be96a.css (636 KiB)
  js/chunk-vendors-legacy.16ddc3e3.js (3.78 MiB)

 warning

entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  dept (4.48 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors-legacy.16ddc3e3.js
      js/chunk-common-legacy.fb11bef5.js
      css/dept.f244a10b.css
      js/dept-legacy.832ef30e.js
  login (4.47 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors-legacy.16ddc3e3.js
      js/chunk-common-legacy.fb11bef5.js
      css/login.ca9fcb83.css
      js/login-legacy.1f2a0ff1.js
  seckill-dept (4.4 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors-legacy.16ddc3e3.js
      js/seckill-dept-legacy.b034e774.js
  test (4.46 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors-legacy.16ddc3e3.js
      js/chunk-common-legacy.fb11bef5.js
      css/test.1461f37b.css
      js/test-legacy.189c5d84.js


 warning

webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

  File                                                          Size                       Gzipped

  ..\seckill\src\main\resources\static\assets\module-js\js\c    3867.06 KiB                1172.18 KiB
  hunk-vendors-legacy.16ddc3e3.js
  ..\seckill\src\main\resources\static\assets\module-js\js\c    60.36 KiB                  18.76 KiB
  hunk-common-legacy.fb11bef5.js
  ..\seckill\src\main\resources\static\assets\module-js\js\d    24.79 KiB                  8.02 KiB
  ept-legacy.832ef30e.js
  ..\seckill\src\main\resources\static\assets\module-js\js\l    6.91 KiB                   2.71 KiB
  ogin-legacy.1f2a0ff1.js
  ..\seckill\src\main\resources\static\assets\module-js\js\t    4.64 KiB                   2.02 KiB
  est-legacy.189c5d84.js
  ..\seckill\src\main\resources\static\assets\module-js\js\s    2.02 KiB                   1.08 KiB
  eckill-dept-legacy.b034e774.js
  ..\seckill\src\main\resources\static\assets\module-js\css\    636.02 KiB                 90.59 KiB
  chunk-vendors.ba1be96a.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    1.97 KiB                   0.79 KiB
  login.ca9fcb83.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    1.97 KiB                   0.79 KiB
  test.1461f37b.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    0.81 KiB                   0.40 KiB
  dept.f244a10b.css

  Images and other types of assets omitted.
  Build at: 2022-06-10T08:21:38.841Z - Hash: 2d3494868caafb73 - Time: 26678ms

me
{
  dept: {
    entry: './src/pages/dept/main.js',
    template: './src/pages/dept/index.html',
    filename: 'dept.html'
  },
  login: {
    entry: './src/pages/login/main.js',
    template: './src/pages/login/index.html',
    filename: 'login.html'
  },
  'seckill-dept': {
    entry: './src/pages/seckill-dept/main.js',
    template: './src/pages/seckill-dept/index.html',
    filename: 'seckill-dept.html'
  },
  test: {
    entry: './src/pages/test/main.js',
    template: './src/pages/test/index.html',
    filename: 'test.html'
  }
}

/  Building module bundle for production...

 WARNING  Compiled with 3 warnings                                                                           下午4:22:01

 warning

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  img/ionicons.6e8059e8.svg (542 KiB)
  img/login-background.6f6c293d.jpg (509 KiB)
  css/chunk-vendors.ba1be96a.css (636 KiB)
  js/chunk-vendors.79d9205a.js (3.72 MiB)

 warning

entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  dept (4.42 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors.79d9205a.js
      js/chunk-common.d48e1dac.js
      css/dept.f244a10b.css
      js/dept.687e9a53.js
  login (4.41 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors.79d9205a.js
      js/chunk-common.d48e1dac.js
      css/login.ca9fcb83.css
      js/login.8b1c482c.js
  seckill-dept (4.34 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors.79d9205a.js
      js/seckill-dept.5d5e7279.js
  test (4.41 MiB)
      css/chunk-vendors.ba1be96a.css
      js/chunk-vendors.79d9205a.js
      js/chunk-common.d48e1dac.js
      css/test.1461f37b.css
      js/test.cc3fae49.js


 warning

webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

  File                                                          Size                       Gzipped

  ..\seckill\src\main\resources\static\assets\module-js\js\c    3810.73 KiB                1152.71 KiB
  hunk-vendors.79d9205a.js
  ..\seckill\src\main\resources\static\assets\module-js\js\c    59.56 KiB                  18.51 KiB
  hunk-common.d48e1dac.js
  ..\seckill\src\main\resources\static\assets\module-js\js\d    23.85 KiB                  7.77 KiB
  ept.687e9a53.js
  ..\seckill\src\main\resources\static\assets\module-js\js\l    6.82 KiB                   2.68 KiB
  ogin.8b1c482c.js
  ..\seckill\src\main\resources\static\assets\module-js\js\t    4.56 KiB                   1.99 KiB
  est.cc3fae49.js
  ..\seckill\src\main\resources\static\assets\module-js\js\s    1.96 KiB                   1.05 KiB
  eckill-dept.5d5e7279.js
  ..\seckill\src\main\resources\static\assets\module-js\css\    636.02 KiB                 90.59 KiB
  chunk-vendors.ba1be96a.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    1.97 KiB                   0.79 KiB
  login.ca9fcb83.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    1.97 KiB                   0.79 KiB
  test.1461f37b.css
  ..\seckill\src\main\resources\static\assets\module-js\css\    0.81 KiB                   0.40 KiB
  dept.f244a10b.css

  Images and other types of assets omitted.
  Build at: 2022-06-10T08:22:01.802Z - Hash: 9e584269e0de4f94 - Time: 20252ms

 DONE  Build complete. The ..\seckill\src\main\resources\static\assets\module-js directory is ready to be deployed.
 INFO  Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html


E:\workspaces\store\my-store\seckill_ui-structure>

这是cmd显示。build成功

3.3查看static包下是否有build后的文件

在这里插入图片描述
有了,build成功

这里有个小插曲,没有将temolates包与static包同级,导致报错Error resolving template template might not exist or might not be accessible

3.4 将js引入到我们的项目中去

vue腳手架build後的dist文件,在html中使用

在这里插入图片描述
在template中创建
vue.html

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
	<title>seckill-dept</title>
	<meta name="description" content="测试" />
	<link href="css/chunk-vendors.ba1be96a.css" rel="stylesheet">
	
<script defer="defer" type="module" th:src="@{/assets/module-js/js/chunk-vendors.79d9205a.js}"></script>
<script defer="defer" type="module" th:src="@{/assets/module-js/js/seckill-dept.5d5e7279.js}"></script>
<link th:href="@{/assets/module-js/css/chunk-vendors.ba1be96a.css}" rel="stylesheet">
<script defer="defer" th:src="@{/assets/module-js/js/chunk-vendors-legacy.16ddc3e3.js}" nomodule></script>
<script defer="defer" th:src="@{/assets/module-js/js/seckill-dept-legacy.b034e774.js}" nomodule></script>
</head>
<body>
    <div id="app">
    </div>
</body>
</html>

在controller_view中

@RestController
@RequestMapping("/view")
public class IndexView {
	
	@GetMapping("/index1")
	public ModelAndView login1() {
		return new ModelAndView("/views/vue");  //路径只需要填写html名字,不需要填写index.html,只需要填写index
	}
}

在yml中

spring:
	thymeleaf: 
    suffix: .html # 过滤所有非html结尾的文件
    classpath: /templates/model/** #则不指定suffix: .html --> 扫描/templates/model/下所有文件
    prefix: classpath:/templates/model/  # 扫描/templates/model/下所有文件
    cache: false # 关闭缓存 开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    encoding: UTF-8
    check-template-location: true  #check-tempate-location: 检查模板路径是否存在
  

运行项目,成功

成功
在这里插入图片描述

4.扩展
打包命令:npm run build
在这里插入图片描述vue serve快速查看组件的运行效果
vue serve

vue serve如果不指定参数默认会在当前目录找以下的入口文件
main.js、index.js、App.vue、app.vue
可以指定哟啊加载的组件
vue serve ./src/Login.vue

在这里插入图片描述页面跳转:

  window.open("http://localhost:9527/seckill/view/dept")
   //this.$router.push({path:'login/index'})
   //this.$router.push({path:'/ddd'}) //多页面无法使用网关,单页面还可以
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值