首页 > 解决方案 > ThymLeaf 将变量传递给 vue js

问题描述

Thymeleaf th:attr 不适用于 Vue 绑定属性

<truncate th:attr="'v-bind:text'=${message}"/>

上面的行在 Vue 和 Thymeleaf 中都没有给我错误,但页面上没有显示

以下是服务器端的响应

附图显示了服务器端的完美响应

一旦我删除'v-bind:'前缀并使用诸如“th:attr =“text = $ {user.comment}”之类的东西,它会按预期工作

<div class="col-lg-12 col-sm-12 col-xs-12 row_block_padding" th:each="user : ${response.users}">

    <!-- OTHER CODE -->
    <div class="col-lg-10 col-sm-10 col-xs-10" style="padding-top: 15px;">
        <truncate th:attr="text=${user.comment}"></truncate>
    </div>
</div>  

标签: vuejs2thymeleaf

解决方案


您需要使用该th:attr指令。例如

<div th:with="message='Simple message'">
  <truncate th:attr="'v-bind:text'=${message}"/>
</div>

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-the-value-of-any-attribute


更新:th:attr与 HTML5 无效属性(如v-bind:text)一起使用,您需要引用属性名称(上面已修复)。

这会产生以下标记

<div>
  <truncate v-bind:text="Simple Message"/>
</div>

您可能会注意到这不是一个有效的 Vue 绑定表达式,因此您可能实际上并不想使用绑定,而是使用

<truncate th:attr="text=${message}"/>

这会产生

<truncate text="Simple message"/>

推荐阅读