在我的Vue.js应用中,我有一个搜索输入,此刻如果搜索为空,它会显示一条错误消息,这很好,但是当用户开始向搜索中添加输入时,我想隐藏它领域。到目前为止,我的组件代码如下,其中显示了模板和脚本区域。
<template>
<div class="jumbotron">
<h1 class="display-4">{{title}}</h1>
<p class="lead">{{intro}}</p>
<hr class="my-4">
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
</p>
<p v-for="(error, index ) in errors" :key="index">{{ error }}</p>
<input
class="form-control form-control-lg mb-3"
type="search"
placeholder="Search"
aria-label="Search"
v-model="search"
required
>
<div class="loading" v-if="loading"></div>
<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>
</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: [],
errors: [],
search: "",
loading: ""
};
},
watch: {
search: function(val) {
if (!val) {
this.result = [];
}
}
},
methods: {
getData: function() {
this.loading = true;
fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
.then(response => response.json())
.then(data => {
this.result = data.results;
this.loading = false;
console.log(data);
});
if (this.search) return true;
this.errors = [];
if (!this.search) this.errors.push("Enter search field.");
}
}
};
</script>
任何想法都很棒,我需要将其添加到v-if
语句中还是在脚本标签中?
答案 0 :(得分:0)
您应注意search
属性,如果未输入search
,则更新错误数组:
methods: {
getData: function() {
this.loading = true;
fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
.then(response => response.json())
.then(data => {
this.result = data.results;
this.loading = false;
console.log(data);
});
}
},
watch: {
search: function(val) {
if (!val) {
this.result = [];
this.errors = [];
this.errors.push("Enter search field.");
}
}
}