Skip to content

thymeleaf和Vue整合

  • 使用场景:需要在thymeleaf里直接使用Vue渲染数据

  • 个人理解:其实二者并没有什么交集,只不过不需要动态加载的数据在路由跳转的时候设置到Model里,通过thymeleaf语法渲染即可,像表格等需要动态渲染的数据,可以通过Vue实例挂载数据

  • 使用一:Vue.js和thymeleaf各自渲染静态数据

    java
    @RequestMapping("/index")
    public String routeToIndexPage(Model model) {
        model.addAttribute("thymeleafMessage", "Hello, Thymeleaf!");
        return "index";
    }
    html
    <!-- index.html -->
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>        
            <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
        </head>
        <body>
            <div id="app">
                <p th:text="${thymeleafMessage}"></p>
                <p>{{ vueMessage }}</p>
            </div>
    
            <script>
                new Vue({
                    el: '#app',
                    data: {
                        vueMessage: 'Hello, Vue!'
                    }
                });
            </script>
        </body>
    </html>
  • 使用二:使用Ajax或Axios获取数据并渲染

    java
    @RequestMapping("/index")
    public String routeToIndexPage(Model model) {
        model.addAttribute("thymeleafMessage", "Hello, Thymeleaf!");
        return "index";
    }
    java
    @ResponseBody
    @GetMapping("/api/getVueData")
    public String getVueData() {
        return "Hello, Vue!";
    }
    html
    <!-- index.html -->
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
            <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
        </head>
        <body>
            <div id="app">
                <p th:text="${thymeleafMessage}"></p>
                <p>{{ vueMessage }}</p>
            </div>
    
            <script>
                new Vue({
                    el: '#app',
                    data: {
                        vueMessage: ''
                    },
    
                    mounted() {
                        axios.get('/api/getVueData')
                            .then(response => {
                            this.vueMessage = response.data;
                        });
                    }
                });
            </script>
        </body>
    </html>
  • 如果需要在<script>标签里获取Model里面的值,可以参考此篇文档:thymeleaf获取Model的值

参考文档

MIT版权,未经许可禁止任何形式的转载