Vue3+typescript implements query function
Keyword query is a very common function, and it is not complicated to realize it. It can be realized not only through the back-end interface, but also in the front-end. Next, I will introduce how to realize the query function through vue3+typescript.
principle:
The query function is realized through the filter() method in Array in typeScript and the indexOf() method in String type
// 查询函数
const onSubmit = () => {
let arr: ListInt[] = []; //定义数组,用来接受查询后需要展示的数据
//判断用户是否输入查询的关键字
if (data.selectData.title) {
//判断两个是否其中一个有值
arr = data.list.filter((value) => {
// 将过滤出来数组赋值给arr
return value.title.indexOf(data.selectData.title) !== -1; //indexOf()没有匹配到关键字则返回-1,区分大小写
});
} else {
arr = data.list;
}
//将查询结果赋值给data.list在页面中展示
data.list = arr;
When the user clears the content of the search box, stops querying or queries again, we need to request back-end data again to ensure that the query proceeds normally.
//监听输入框中的内容
watch(
[() => data.selectData.title],
() => {
// 如果输入框中的内容为空,则再次请求数据
if (data.selectData.title === "") {
getGoodsList().then((res) => {
//将查询结果赋值给data.list
data.list = res.data;
});
}
}
);