简体   繁体   English

如何用Vue访问Spring Boot model?

[英]How to access Spring Boot model with Vue?

I am not sure how to access a model I create with my controller with Vue in my html. I know how to access model attributes with thymeleaf, but cannot find any info anywhere on how to access them with Vue.我不确定如何在我的 html 中使用 Vue 访问我使用 controller 创建的 model。我知道如何使用 thymeleaf 访问 model 属性,但无法在任何地方找到有关如何使用 Vue 访问它们的任何信息。 I would like to store the count value from the controller in the Vue data count I have below.我想将 controller 的计数值存储在下面的 Vue 数据计数中。 I am using Vue within my template hosted with CDN, not as a separate project.我在 CDN 托管的模板中使用 Vue,而不是作为一个单独的项目。

Here is my controller:这是我的 controller:

@PostMapping("/word")
public String searchSentence(@ModelAttribute WordSearch wordSearch, Model model) {
    int c = wordSearch.search();
    String count = String.valueOf(c);
    model.addAttribute("wordSearch", wordSearch);
    model.addAttribute("count", count);
    return "count";
}

Here is the count.html:这是 count.html:

 <:DOCTYPE HTML> <html xmlns:th="https.//www.thymeleaf;org"> <head> <title>Count-Form</title> <meta http-equiv="Content-Type" content="text/html: charset=UTF-8" /> <script src="https.//cdn:jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h1>Result</h1> <p th:text="'sentence. ' + ${wordSearch:sentence}" /> <p th:text="'word. ' + ${wordSearch:word}" /> <:--<p th:text="'count: ' + ${count}" /> --> <div id="count-text" style="display: none"> <p th,text="${count}" /> </div> <div id="app"> {{count}} </div> <script> new Vue({ el: '#app', data() { return { count. "" } }? created() { this?count =??? } }) </script> <a href="/greeting">Submit another message</a> </body> </html>

You can follow this blog to do what you desire.你可以关注这个博客来做你想做的事。 https://dev.to/brunodrugowick/spring-boot-vue-js-axios-and-thymeleaf-with-bootstrap-in-4-commits-2b0l . https://dev.to/brunodrugowick/spring-boot-vue-js-axios-and-thymeleaf-with-bootstrap-in-4-commits-2b0l In this author explains how you can use Thymeleaf and VueJS together by adding VueJS dependency in pom.xml.在本文中,作者解释了如何通过在 pom.xml 中添加 VueJS 依赖项来同时使用 Thymeleaf 和 VueJS。

you need following dependency in your pom xml to use VueJS,你需要在你的 pom xml 中使用 VueJS,

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>vue</artifactId>
    <version>2.6.11</version>
</dependency> 

Thymeleaf is a server-side Java template engine, while Vue is a JS framework to build frontend layer. Thymeleaf 是一个服务器端的 Java 模板引擎,而 Vue 是一个构建前端层的 JS 框架。 The best way to connect Spring with Vue would be by an API.将 Spring 与 Vue 连接的最佳方式是使用 API。 So you'll need to expose your data as a JSON, make a http call vue app -> java api and consume the response. So you'll need to expose your data as a JSON, make a http call vue app -> java api and consume the response.

Here you can find more details, how this works 在这里你可以找到更多细节,这是如何工作的

All you have to do is create a method returning ResponseBody, then you call this method in Vue (Axios is a good option.): Example 1: function to get a String variable:您所要做的就是创建一个返回 ResponseBody 的方法,然后在 Vue 中调用该方法(Axios 是一个不错的选择。):示例 1:function 以获取 String 变量:

@GetMapping( "/getLanguage")
    @ResponseBody
    public String obtenerIdiomaActual() {
         return languageService.getLanguage();
    }

Then you'd need a method in your Vue app to read this value:然后你需要在你的 Vue 应用程序中使用一个方法来读取这个值:

const vm = Vue.createApp({
    data() {
        return {
            language: null,
        }
    },
    methods: {
        getLanguage() {
            axios.get(window.location.origin + '/getLanguage')
                .then(response => {
                    this.language = response.data;
                })
                .catch(error => {
                    this.errorMessage = error.message;
                    console.error("There was an error!", error);
                });
        },
   
    mounted: function () {
        this.getLanguage();
    },
    watch: {
        idioma: function () {
            console.log("Language: " + this.language);
        }
    },
}).mount('#myApp')

You can use all kind of complex data: objects, arrays, dictionaries (maps)...您可以使用各种复杂的数据:对象、arrays、字典(地图)...

 @GetMapping( "/getComplexData")
    @ResponseBody
    public Map<String, List<SpaceBean>> getMyComplexData() ...

And read the response easily with Vue:并使用 Vue 轻松阅读响应:

<div  v-for="(spaceList, key) in datos">
    <p v-cloak><b>{{key}}</b></p>
        <table  class="display" style="width: 100%" v-cloak>
            <tbody>
            <tr v-for="space in spaceList">
                <td>{{space.alias}}</td>
                <td>{{space.descripcion}}</td>
                <td>{{space.url}}</td>
            </tr>
            ...

I hope this help a little!!我希望这能有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM