1. 程式人生 > 程式設計 >SpringBoot整合vue的開發解決方案

SpringBoot整合vue的開發解決方案

最近由於工作要求:前端採用vue開發,後端採用springboot開發,前後端分離開發,最後前端頁面又整合到後端來。經歷多次採坑,總結以下方案:

vue build後的檔案部署到springboot目錄

vue打包後,會生成dist目錄

vue打包後的dist目錄

springboot靜態資源目錄如下:

在這裡插入圖片描述

SpringBoot處理靜態資源和頁面,設定如下:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
 	registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
	super.addResourceHandlers(registry);
}

頁面模板設定,如下:

#頁面模板設定
spring.thymeleaf.option=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

部署方案
dist的index.html 直接放在templates目錄下
dist的css、fonts、img、js 直接放在static目錄下

vue打包後vendor檔案過大的優化方案

vue使用vue-cli打包後,vendor就將vue.js其他引用的包一起壓縮打包進去,導致vendor檔案超過1M,影響頁面載入速度
本專案使用了vue、vue-router、iview、axios、echarts等
(1)使用vue、vue-router、iview、axios、echarts等cnd引用
在index.html檔案中,增加:

<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-router.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/iview.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/echarts.min.js"></script>

(2)打包時,排除vue、vue-router、iview、axios、echarts等打包
在webpack.base.conf.js檔案中,module.exports={…} 方法中新增

module.exports = {
	...
	externals:{
	  'vue':'Vue','axios':'axios','vue-router':'VueRouter','iview':'iview','echarts':'echarts',},...
}

這裡有注意的是:命名問題
比如:vue-router的在https://unpkg.com/[email protected]/dist/vue-router.min.js中預設採用VueRouter,所以在import vue-router一定要使用VueRouter,而不能使用其他別名。

vue預設別名是Vue
axios預設別名是axios
vue-router預設別名是VueRouter
iview預設別名是iview
echarts預設別名是echarts

例子:

import Vue from 'vue'
import VueRouter from 'vue-router'
import iview from 'iview'
import echarts from 'echarts'

Vue.use(VueRouter)

export default new VueRouter({
 mode: 'history',...
})

(3)vue-router的路由頁面設定為按需載入

export default new VueRouter({
 mode: 'history',routes: [
  //頁面1
  {
   path: '/Page1',name: 'page1',component: () => import('@/views/Page1.vue')
  },//頁面2
  {
   path: '/Page2',name: 'page2',component: () => import('@/views/Page2.vue')
  }
 ]
 });

(4)重新打包後vendor.js檔案就小了,可以小到1k哦

vue-router使用了history模式,vue其實做的是單頁面應用,但是效果看上去是多個不同頁面,問題來了,部署到線上環境後,該如何配置?

百度上有很多處理方案,比如:使用errorPage方式處理,nginx配置等,這些問題比較繁瑣,而且在部署過程中,一堆問題。
經過多次嘗試,發現有一個最簡單方法,Controller直接url路徑配置到index.html即可,而且輕鬆解決history模式帶來的後端問題,如下:

@ApiOperation(value = "",hidden = true)
@RequestMapping(path = "/Page1")
public String page1() {
  return "index";
}

@ApiOperation(value = "",hidden = true)
@RequestMapping(path = "/Page2")
public String page2() {
  return "index";
}

這種方案非常有利於後端開發人員做更多的進一步操作,比如:給每個頁面增加頁面許可權等。
注意:該方案目前適用於前端頁面整合到後端的專案工程。

到此這篇關於SpringBoot整合vue的開發解決方案的文章就介紹到這了,更多相關SpringBoot整合vue內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!