0

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

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>`
})
4

1 回答 1

1

只需添加一个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" />

仅当输入具有值时才提交表单。

于 2020-01-21T09:16:21.350 回答