【发布时间】:2020-01-21 09:06:18
【问题描述】:
我试图使用 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/onSubmit?创建一个新函数来执行需要完成的操作,然后通过 onclick/onsubmit vuejs.org/v2/guide/events.html 触发该新方法 -
我发现最麻烦的是将表单包装到 vue 元素中,因为模板只会覆盖我的 html。
-
您实际上并不需要正确的
<form>,因为 Javascript 正在通过 AJAX 处理提交/请求。所以我会亲自摆脱它 -
为什么不把你所有的searchBar代码移到vue模板呢?
标签: javascript html rest vue.js get