代碼
按鈕
<el-button type="text" style="position: absolute;top:-48px;right:260px;z-index: 99;color: #000;"@click="handleButtonClick('搜索'), showConfirmationModal2()" :class="{ 'blue-text': activeButton === '搜索' }"><img src="../../assets/svg/搜索.svg" style="width: 1.2vw;" />搜索</el-button>
搜索模態框
<!-- 搜索模態框 --><div style="z-index: 1001;position: relative;"><el-dialog v-model="modalVisible2" title="搜索" @close="handleModalClose2"><div><span>請輸入搜索內容:</span><el-input v-model="keyword"></el-input></div><div style="display: flex; justify-content: space-between;"><el-button @click="handleCancel2">取消</el-button><el-button type="primary" @click="handleConfirm2">確定</el-button></div></el-dialog></div>
js代碼
//查詢
var keyword = ref()
// 定義一個函數,用于模糊查詢
function searchMessages() {// 使用filter()方法進行篩選const result = datas.value.filter(item => {// 使用正則表達式匹配關鍵字const regex = new RegExp(keyword.value, 'i');// 在標題和內容中查找匹配的項return regex.test(item.title) || regex.test(item.content);});// 返回查詢結果return result;
}
const modalVisible2 = ref(false)
// 點擊按鈕顯示模態框
const showConfirmationModal2 = () => {modalVisible2.value = true;}
// 用戶點擊取消按鈕
const handleCancel2 = () => {fetchData1()modalVisible2.value = false;
}
// 用戶點擊確定按鈕
const handleConfirm2 = () => {data.value = [];data1.value = [];data2.value = [];// 調用相應的方法,進行設置console.log(datas.value)datas.value = searchMessages();console.log(datas.value)datas.value.forEach(item => {console.log(item)switch (item.typeid) {case 0:data.value.push(item);break;case 1:data1.value.push(item);break;case 2:data2.value.push(item);break;}});// 關閉模態框modalVisible2.value = false;
}
// 處理模態框關閉事件
const handleModalClose2 = () => {// 處理模態框關閉時的邏輯modalVisible2.value = false;
}
核心代碼
使用filter以及正則i對數據進行處理
const result = datas.value.filter(item => {
// 使用正則表達式匹配關鍵字
const regex = new RegExp(keyword.value, ‘i’);
// 在標題和內容中查找匹配的項
return regex.test(item.title) || regex.test(item.content);
});