Vue实现分类与搜索
tips:这是使用vue3组合式api实现的,需要将App.vue替换成下面的代码,之后运行就可以了
<script setup>
import { ref, watchEffect, watch } from 'vue';
const mock = [
{ name: "小王", sex: 0 },
{ name: "小红", sex: 1 },
{ name: "小李", sex: 1 },
{ name: "小张", sex: 0 }
];
const showDatas = ref([]);
const queryAllData = () => {
// 模拟请求过程
setTimeout(() => {
showDatas.value = mock;
}, 3000);
};
const sexFliter = ref(-1);
const searchKey = ref("");
/*
watchEffect(() => {
if (sexFliter.value == -1) {
showDatas.value = mock;
} else {
showDatas.value = mock.filter((data) => {
return data.sex == sexFliter.value;
});
}
});
*/
watch(sexFliter, (newValue, oldValue) => {
if (newValue == -1) {
showDatas.value = mock;
} else {
showDatas.value = mock.filter((data) => {
return data.sex == newValue;
});
}
});
watchEffect(() => {
if (searchKey.value.length == 0) {
showDatas.value = mock;
} else {
showDatas.value = mock.filter((data) => {
return data.name.search(searchKey.value) != -1;
});
}
});
</script>
<template>
<div class="container">
<div class="content">
<input type="radio" :value="-1" v-model="sexFliter" />全部
<input type="radio" :value="0" v-model="sexFliter" />男
<input type="radio" :value="1" v-model="sexFliter" />女
</div>
<div class="content">搜索:<input type="text" v-model="searchKey" /></div>
<div class="content">
<table>
<tr>
<th>姓名</th>
<th>性别</th>
</tr>
<tr v-for="(data, index) in showDatas" :key="index">
<td>{{ data.name }}</td>
<td>{{ data.sex == 0 ? '男' : '女' }}</td>
</tr>
</table>
</div>
</div>
</template>
<style scoped>
.container {
margin: 50px;
}
.content {
margin: 20px;
}
table,
th,
td {
border: 1px solid black;
width: 300px;
text-align: center;
}
</style>
感谢各位的阅读,更多文章请前往九天小窝。