[英]How to incorporate a search query box into api call in Vue.js
So far I can get the data in a table when I hard code an artists name.到目前为止,当我硬编码艺术家姓名时,我可以在表格中获取数据。 What I want is my search box to link into the api call, so when I search for an artist, those results show up, I am new to Vue.
我想要的是我的搜索框链接到 api 调用,所以当我搜索艺术家时,这些结果会显示出来,我是 Vue 的新手。 I have created so far, I think the api call would need to be something like:
到目前为止,我已经创建了,我认为 api 调用需要类似于:
https://itunes.apple.com/search?term=${this.search}&entity=album
<template>
<div class="jumbotron">
<h1 class="display-4">{{title}}</h1>
<p class="lead">{{intro}}</p>
<hr class="my-4">
<form class="col-lg-6 col-sm-12 mr-auto ml-auto">
<input
class="form-control form-control-lg mb-3"
type="search"
placeholder="Search"
aria-label="Search"
>
<table class="table table-sm table-light table-bordered" v-if="result.length">
<thead class="thead-dark">
<tr class="col-8">
<th scope="col">Name</th>
<th scope="col">Artist</th>
</tr>
</thead>
<tbody>
<tr v-for="(result, index) in result" :key="index">
<td>{{result.collectionName}}</td>
<td>{{result.artistName}}</td>
</tr>
</tbody>
</table>
<button
class="btn btn-success btn-lg btn-block mb-3"
type="submit"
v-on:click="getData"
v-if="result.length < 1"
>Get data</button>
</form>
</div>
</template>
<script>
export default {
name: "Hero",
props: {
navLink: String
},
data: function() {
return {
title: "Simple Search",
intro: "This is a simple hero unit, a simple jumbotron-style.",
subintro:
"It uses utility classes for typography and spacing to space content out.",
result: [],
search: ""
};
},
watch: {
search: function(val) {
if (!val) {
this.result = [];
}
}
},
methods: {
getData: function() {
fetch(
"https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=drake&entity=album"
)
.then(response => response.json())
.then(data => {
this.result = data.results;
console.log(data);
});
}
}
};
</script>
<style>
.jumbotron {
margin-bottom: 0rem !important;
}
.table {
width: 100% !important;
}
</style>
As you can see I have hard coded the artist 'Drake" just to experiment, but how can I link it to the input search?如您所见,我对艺术家“Drake”进行了硬编码只是为了进行实验,但是如何将其链接到输入搜索?
It's pretty easy.这很容易。 Let me describe.
让我描述一下。
button
inside the form
causes page reloading but you don't need it. form
内的button
会导致页面重新加载,但您不需要它。<!--<form class="col-lg-6 col-sm-12 mr-auto ml-auto">-->
... some useful code inside ...
<!--</form>-->
v-model
v-model
将输入字段与您的模型连接起来<input
....
aria-label="Search"
v-model="search"
>
this.search
.this.search
时使用模型。 The data have to be provided reactively.fetch(
`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=${this.search}&entity=album`
)
You may learn more about connection forms and vue's model in the documentation您可以在文档中了解更多关于连接形式和 vue 模型的信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.