如何在Spring Boot Thymeleaf项目中整合Vue.js并同端口运行?
在Thymeleaf视图项目中整合Vue.js(同一端口+同HTML)
完全可以在同一个HTML文件中同时使用Thymeleaf和Vue.js,而且不用拆分服务到不同端口,也不需要把@Controller改成@RestController,下面是具体实现方案:
1. 引入Vue.js到Thymeleaf页面
直接在Thymeleaf模板中引入Vue资源即可,两种方式任选:
- CDN引入:适合快速测试或小型项目,直接在页面
<head>或<body>末尾添加CDN链接 - 本地引入:把Vue的js文件放到Spring项目的
src/main/resources/static/js目录下,用Thymeleaf资源引用语法引入:<script th:src="@{/js/vue.js}"></script>
2. 解决语法冲突(核心问题)
Thymeleaf和Vue默认都用{{}}作为插值符号,会导致解析冲突,两种解决办法:
方法一:修改Vue的插值分隔符
初始化Vue实例时,通过delimiters配置替换成其他符号(比如[[ ]]),两边语法就不会互相干扰:
new Vue({ el: '#app', delimiters: ['[[', ']]'], // 自定义Vue插值符号 data() { return { vueText: 'Vue渲染的内容' } } })
之后Vue部分用[[ vueText ]]渲染数据,Thymeleaf继续用{{ backendData }}或th:text="${backendData}"。
方法二:Thymeleaf避免直接用{{}}
如果不想改Vue配置,Thymeleaf的后端数据渲染全部用th:text、th:utext等属性,不用原生{{}},这样Vue的{{}}就能正常使用:
<!-- Thymeleaf用th:text渲染后端数据 --> <div th:text="${backendMsg}"></div> <!-- Vue正常用{{}} --> <div id="app">{{ vueMsg }}</div>
3. 同一端口运行的配置
不需要单独启动Vue服务,把Vue的所有资源(js、css、组件文件)放到Spring项目的static目录下,启动Spring应用(默认8080)后,直接通过Spring端口访问页面即可。
如果你的Vue部分用Vue CLI开发:
- 开发阶段:配置
vue.config.js,把API请求代理到Spring端口,避免跨域同时保留Vue热重载:
module.exports = { devServer: { proxy: { '/api': { // 匹配所有/api开头的请求 target: 'http://localhost:8080', // Spring项目地址 changeOrigin: true } } } }
- 生产阶段:执行
npm run build打包Vue项目为dist目录,把dist内所有文件复制到Spring的static目录,或直接配置Spring视图解析器指向dist目录。
完整示例代码
Thymeleaf模板(src/main/resources/templates/home.html)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf + Vue Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <!-- Thymeleaf负责渲染的区域 --> <div class="backend-content"> <h2 th:text="${pageTitle}"></h2> <p th:text="${backendInfo}"></p> </div> <!-- Vue负责渲染的区域 --> <div id="vue-app"> <h3>[[ vueTitle ]]</h3> <p>当前计数:[[ count ]]</p> <button @click="increaseCount">点击加1</button> </div> <script> new Vue({ el: '#vue-app', delimiters: ['[[', ']]'], data() { return { vueTitle: 'Vue组件区', count: 0 } }, methods: { increaseCount() { this.count++ } } }) </script> </body> </html>
Spring Controller
@Controller public class DemoController { @GetMapping("/") public String index(Model model) { model.addAttribute("pageTitle", "Thymeleaf渲染的页面标题"); model.addAttribute("backendInfo", "这是从Spring后端传递过来的信息"); return "home"; // 返回templates下的home.html } }
启动Spring项目后,访问http://localhost:8080就能看到Thymeleaf和Vue同时渲染的内容,完全在同一端口运行。
内容的提问来源于stack exchange,提问作者An Nguyen Thanh
相关产品推荐
相关产品推荐

