<template>
<view>
<input type="text" v-model="text" placeholder="輸入..........">
<button type="default" @click="serachFn">搜索</button>
<view>
<view class="title">歷史記錄 <text @click="deleteFn">shanchu</text></view>
<view>
<block v-for="( item,index) in history">
<text class="box">
{{item}}
</text>
</block>
</view>
</view>
</view>
</template>
<script>
export default{
data(){
return{
history:[], //歷史記錄數組
text:"" //搜索內容
}
},
onShow(){
var that=this;
// 頁面顯示獲取搜索歷史記錄信息
uni.getStorage({
key: 'history_key',
success:function(res) {
console.log(res.data);
console.log("獲取緩存成功");
that.history=res.data;
}
});
},
methods:{
serachFn(){
// 如果為空則不判斷直接返回
if(!this.text.trim()){
return
}
// 查找關鍵字是否已存在 存在返回第一個查找到的內容 不存在返回undefined
let index=this.history.find(item=>item==this.text.trim());
if(!index){
// 未查找到情況下 歷史記錄前面增加一條信息
this.history.unshift(this.text);
// 超過5條刪除最后一個 保證一直是顯示5條內容
if(this.history.length>5){
this.history.pop();
}
// 存入緩存
uni.setStorage({
key: 'history_key',
data: this.history,
success: function () {
console.log('success');
}
});
}
},
deleteFn(){
var that=this;
uni.showModal({
title: '提示',
content: '這是一個模態彈窗',
success: function (res) {
if (res.confirm) {
that.history=[];
uni.setStorage({
key: 'history_key',
data: that.history,
success: function () {
console.log('success');
}
});
console.log('用戶點擊確定');
} else if (res.cancel) {
console.log('用戶點擊取消');
}
}
});
}
}
}
</script>
<style>
input{ height: 40px; margin: 10px; outline: 1px solid red; padding-left: 10px;}
.box{ padding: 5px 10px; border: 1px solid #ddd; margin: 10px;}
.title{ margin: 20px;}
</style>