Reputation: 183
I was trying to send a GET
request using vue, but now I'm trying to extend it's functionality. I would like to bind sending the request to the form's submit button, and also pass a param from textfield in the form I've created.
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>`
})
Upvotes: 0
Views: 4325
Reputation: 3614
Simply add an onclick
listener and bind it with a method:
<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))
}
}
}
As for the param, you can simply keep track of the value using $ref
. Although there are many alternatives.
<input ref="input" type="text" placeholder="Search" />
The form is only submitted if the input has a value.
Upvotes: 1