繁体   English   中英

Vuejs 使用方法发送 GET 请求

[英]Vuejs sending a GET request with a method

我试图使用 vue 发送GET请求,但现在我正在尝试扩展它的功能。 我想将发送请求绑定到表单的提交按钮,并在我创建的表单中从文本字段传递一个参数。

HTML

<html>
<head>
     <meta charset="UTF-8">
     <link rel="stylesheet" type="text/css" href="Bookstyle.css"> 
</head>
<body>
    <div class="navbar">
        <a href="#contact">Cart</a>
        <a href="#about">Orders</a>
        <a href="#profil">Profile</a>
        <form id="searchbar">
            <input type="text" placeholder="Search"> </input> // the input I want to send as paramValue
            <input id="sendButton" type="submit" value="search"> // the button to trigger sending the request
        </form>
    </div>
    <div id="app"></div>
</body>
    <script src="https://unpkg.com/axios/dist/axios.min.js" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript"></script>
    <script src="./script.js" type="text/javascript"></script>
</html>

JS

const app = new Vue({
    el: "#app",
    data: {
        paramValue: "test", // the parameter currently bound like this for test purposes
        bookResponse: [],
    },
        mounted() {
            axios
                .get("http://localhost:8080/Books/getByParam/{param}", {
                    params: {
                        param: `${this.paramValue}`
                    }   
                })
                .then(response => (this.bookResponse = response.data))
    },
    template: `
        <div id = "displayReturnedValue">
            <p v-for="book in bookResponse" style="font-size:20px;">
                Title:{{book.title}} 
                Publisher:{{book.publisher}}
                Price:{{book.price}} 
                Availability:{{book.availability}}
                Category:{{book.categoryid.category}}
                Author:{{book.authorid.firstname}} {{book.authorid.lastname}}
            </p>
        </div>`
})

只需添加一个onclick侦听器并将其与方法绑定:

<input id="sendButton" type="submit" value="search" @click="sendRequest()> 
methods: {
    sendRequest() {
        if (this.$refs.input.value) {
            axios.get("http://localhost:8080/Books/getByParam/{param}", {
                params: {
                    param: this.$refs.input.value
                }   
            })
            .then(response => (this.bookResponse = response.data))
        }
    }
}

至于参数,您可以使用$ref简单地跟踪值。 虽然有很多选择。

<input ref="input" type="text" placeholder="Search" />

只有当输入有值时才会提交表单。

暂无
暂无

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

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