Vue 通过点击按钮搜索显示数组元素
Vue displaying array elements via search on button click
我正在学习 Vue Js,我发现自己在这里有点迷路。我想根据您搜索的 ID 显示来自 Rest API 的数组元素。例如:我的 Json 文件包含具有不同 ID 的不同人,如果我搜索一个特定的 ID,我想显示该人的确切信息以及分配给他的 ID。
所以我尝试使用 array.filter 函数,但是我将搜索中的 creditId 值分配给 url 查询。 ("http://localhost:8080/#/search?creditid=123") 我希望查询调用显示信息函数。
所以这些是我从我的 REST API 获取数据并在搜索栏中推送值的 creditid 查询。
export default {
name: 'app',
data(){
return{
creditid: '',
credits: [],
userFilterKey: ''
}
},
mounted() {
this.$http.get('http://localhost:3000/credits')
.then(function (res) {
this.credits = res.body;
})
.catch(function (error) {
console.log('Error: ', error);
})
},
methods: {
pushing(creditid) {
this.$router.push({name: 'search', query: {creditid}});
}
}
}
这是我的搜索输入和搜索按钮:
<div class="container">
<input for="search-credit" class="form-control" type="text" placeholder="Credit ID" aria-label="Search" v-model.trim="creditid">
<router-view/>
<button type="button" class="btn btn-primary" id="search-credit" @click="pushing(creditid)">Search</button>
</div>
我的 JSON 文件如下所示:
[
{
"creditId": 123,
"id": 1,
"client": "Tom",
"sport": "basketball"
},
{
"creditId": 789,
"id": 2,
"client": "Peter",
"sport": "soccer",
}
]
总而言之:我想根据您在搜索输入中键入的 creditid 来显示此人的数据。
您应该使用 computed property
过滤掉您在 mounted 钩子中获取的结果。您可以在此处查看具有类似功能的 vue.js 文档示例 - https://vuejs.org/v2/guide/list.html#v-for-with-a-Component.
如果你想为每个搜索请求单独调用 API,那么只需实现搜索方法并使用你的 this.creditid
作为参数并将 credits
数组替换为 API 响应数据 - 示例 https://jsfiddle.net/qrwn568g/1/(为 http 请求处理添加了 axios,为一些样式添加了 tailwind)
我正在学习 Vue Js,我发现自己在这里有点迷路。我想根据您搜索的 ID 显示来自 Rest API 的数组元素。例如:我的 Json 文件包含具有不同 ID 的不同人,如果我搜索一个特定的 ID,我想显示该人的确切信息以及分配给他的 ID。
所以我尝试使用 array.filter 函数,但是我将搜索中的 creditId 值分配给 url 查询。 ("http://localhost:8080/#/search?creditid=123") 我希望查询调用显示信息函数。
所以这些是我从我的 REST API 获取数据并在搜索栏中推送值的 creditid 查询。
export default {
name: 'app',
data(){
return{
creditid: '',
credits: [],
userFilterKey: ''
}
},
mounted() {
this.$http.get('http://localhost:3000/credits')
.then(function (res) {
this.credits = res.body;
})
.catch(function (error) {
console.log('Error: ', error);
})
},
methods: {
pushing(creditid) {
this.$router.push({name: 'search', query: {creditid}});
}
}
}
这是我的搜索输入和搜索按钮:
<div class="container">
<input for="search-credit" class="form-control" type="text" placeholder="Credit ID" aria-label="Search" v-model.trim="creditid">
<router-view/>
<button type="button" class="btn btn-primary" id="search-credit" @click="pushing(creditid)">Search</button>
</div>
我的 JSON 文件如下所示:
[
{
"creditId": 123,
"id": 1,
"client": "Tom",
"sport": "basketball"
},
{
"creditId": 789,
"id": 2,
"client": "Peter",
"sport": "soccer",
}
]
总而言之:我想根据您在搜索输入中键入的 creditid 来显示此人的数据。
您应该使用 computed property
过滤掉您在 mounted 钩子中获取的结果。您可以在此处查看具有类似功能的 vue.js 文档示例 - https://vuejs.org/v2/guide/list.html#v-for-with-a-Component.
如果你想为每个搜索请求单独调用 API,那么只需实现搜索方法并使用你的 this.creditid
作为参数并将 credits
数组替换为 API 响应数据 - 示例 https://jsfiddle.net/qrwn568g/1/(为 http 请求处理添加了 axios,为一些样式添加了 tailwind)