【uni-app】实现搜索框、历史记录等详细操作

Uni-app实现搜索框、历史记录传值、点击历史记录跳转页面等操作

input输入框:官网教程

v-model 参数:是一个用于实现双向数据绑定的指令。它允许将表单元素的值与Vue实例的数据对象属性进行关联,从而实现数据的同步更新。

使用v-model指令绑定表单元素的值。例如代码这里的<input type="text" value="" placeholder="搜索" v-model="keyword" @confirm="searchAction" />,这里将input元素的值绑定到了实例的keyword属性上。

网页代码

<template>
	<view>
		<view class="form">
			<view class="form-input">
                <!-- 可代替使用uniapp扩展组件的uni-icons 具体在https://uniapp.dcloud.net.cn/component/uniui/uni-icons.html
				-->
				<image src="../../static/images/icon-search.png" mode="widthFix"></image>
				<input type="text" value="" placeholder="搜索" v-model="keyword" @confirm="searchAction" />
			</view>
			<view class="cancel" @click="navigateBack">取消</view>
		</view>
        <view class="history">
			<view class="history-head">
				<text>搜索历史</text>
				<image src="../../static/images/icon-trash.png" mode="widthFix" @click="cleanHistory"></image>
			</view>
			<view class="history-list">
				<scroll-view v-for="item in historyList" @click="navigateToDetail(item)">
					{{ item }}
				</scroll-view>
			</view>
		</view>
	</view>
</template>

style样式(自由发挥)

一定要加lang=“scss”,这样才可以完成嵌套样式操作

<style lang="scss" scoped>
	.form {
		background: white;
		display: flex;
		align-items: center;
		padding: 30rpx;

		.cancel {
			color: #666;
			margin-left: 20rpx;
			font-size: 28rpx;
		}
	}

	.form-input {
		display: flex;
		align-items: center;
		flex: 1;
		background-color: #f5f5f5;
		border-radius: 80rpx;
		padding: 0 10rpx;

		image {
			display: block;
			width: 36rpx;
			margin: 0 20rpx;
			flex-shrink: 0;
		}

		input {
			display: block;
			flex: 1;
			font-size: 28rpx;
			color: black;
			height: 70rpx;
			line-height: 70rpx;
		}
	}

	.history {
		background: white;
		padding: 30rpx;

		.history-head {
			display: flex;
			align-items: center;

			text {
				display: block;
				flex: 1;
				font-size: 32rpx;
				font-weight: bold;
				color: black;
			}

			image {
				display: block;
				width: 40rpx;
			}
		}
	}

	.history-list {
		scroll-view {
			display: inline-block;
			vertical-align: top;
			background-color: #f1f1f1;
			color: #333;
			font-size: 18px;
			padding: 10rpx 20rpx;
			border-radius: 40rpx;
			margin: 20rpx 20rpx 0 0;
			width: fit-content;
		}
	}
</style>

接口版脚本

//引入的模板,config.js 通常包含应用程序的配置信息,例如API的基础URL、全局变量、常量等。
import config from '../../utils/config.js';
//request.js 通常封装了网络请求的逻辑,使用了 uni.request 或其他HTTP库来发送请求。
import request from '../../utils/request.js';
//utils.js 通常包含一些通用的工具函数或实用程序,例如日期格式化、字符串处理、数组操作等。
import utils from '../../utils/utils.js';
return {
	keyword:'',//默认为空
	historyList:[]//数组默认为空
},

method代码

searchAction(e) {
    // 保存历史记录
    if (this.keyword !== '' && !this.historyList.includes(this.keyword)) {
        // 查询是否有口令,直接跳到详情页
        this.codeSearch();
    } else if (this.historyList.includes(this.keyword)) {
        this.codeSearch();
    } else {
        return uni.showToast({
            title: '请输入你要搜索的创作者',
            icon: 'none'
        });
    }
},
async codeSearch() {
    // 显示一个加载提示框,提示用户正在查询中
    uni.showLoading({
        title: '正在查询中...'
    });

    let _this = this; // 保存当前上下文的引用

    // 发送一个POST请求到指定的API地址,并等待响应
    const r = await request({
        url: `${接口.API}api/文件名/search`,
        method: 'POST',
        data: {
            code: this.keyword // 将当前对象的keyword属性作为请求数据的一部分发送
        }
    });

    // 隐藏加载提示框
    uni.hideLoading();

    // 检查响应的错误码是否为0(表示成功)
    if (r.error_code === 0) {
        // 如果成功,清空历史记录列表
        this.historyList = [];
        // 将当前的keyword添加到历史记录列表的最前面
        this.historyList.unshift(this.keyword);
        // 将更新后的历史记录列表保存到本地存储
        uni.setStorageSync('historyList', this.historyList);
        // 导航到详情页面,并传递用户ID和用户代码作为参数
        uni.navigateTo({
            //这里的url写你要跳转的详情页面后面跟着你要查询的用户id
            url: '/pages/talent/detail?id=' + r.data.user_id + '&code=' + r.data.user_code
        });
        console.log(r.error_code); // 打印错误码(这里应该是0)
    } else {
        // 如果失败,打印当前的历史记录列表
        console.log(this.historyList);
        // 显示一个提示框,告知用户查询失败的原因
        return uni.showToast({
            title: r.msg, // 使用响应中的消息内容作为提示信息
            icon: 'none' // 不显示图标
        });
    }

    // 输入完成后清空搜索框
    this.keyword = '';
}
onLoad() {
	//页面展示出存储到本地的历史记录数据
	const historyList = uni.getStorageSync('historyList');
	this.historyList = historyList;
},
 cleanHistory() {
	uni.showModal({
		content: '是否清除历史记录',
        success: (res) => {
             if (res.confirm) {
             	// 清除本地存储中的历史记录数据
             	uni.removeStorageSync('historyList');
             	this.historyList = [];
             }
        }
    });
},
//这一步是为了实现在历史记录中点击数据可以继续转到对应的详细页面
//传入参数item,也就是你在数组里的数据
navigateToDetail(item){
	//将传入的参数赋值给搜索的参数
    this.keyword = item;
    //继续检查此数据是否存在数组、历史记录中,是的话直接跳转到详情页面。
    this.searchAction();
}
navigateBack() {
	//如果不想搜索,返回上一级页面
	uni.navigateBack();
},

json文件版脚本

  1. 首先创建一个json文件
[
    {
        "id": "1",
        "name": "创作者A",
        "code": "CODE123"
    },
    {
        "id": "2",
        "name": "创作者B",
        "code": "CODE456"
    }
]
  1. 在你的页面或组件中导入这个JSON文件,并使用它作为数据源。修改你的export default部分如下:
import data from '../../utils/data.json'; // 导入本地数据
keyword: '',
historyList: [],
localData: data // 使用本地数据
onLoad() {
    //在页面加载时,从本地存储中读取历史记录并赋值给historyList。
    //如果本地存储中没有历史记录,则初始化为空数组。
    this.historyList = uni.getStorageSync('historyList') || [];
},

方法解释同上(其他版本)

searchAction(e) {
    if (this.keyword !== '' && !this.historyList.includes(this.keyword)) {
        this.codeSearch();
    } else if (this.historyList.includes(this.keyword)) {
        this.codeSearch();
    } else {
        return uni.showToast({
            title: '请输入你要搜索的创作者',
            icon: 'none'
        });
    }
},
async codeSearch() {
    uni.showLoading({
        title: '正在查询中...'
    });
    // 使用本地数据进行搜索
    const foundItem = this.localData.find(item => item.code === this.keyword);
    uni.hideLoading();
    // 如果本地数据存在
    if (foundItem) {
        //在本地数据中查找与用户输入的关键词匹配的项
        this.historyList = [this.keyword, ...this.historyList];
        // 将当前的keyword添加到历史记录列表的最前面
        this.historyList.unshift(this.keyword);
        // 将更新后的历史记录列表保存到本地存储
        uni.setStorageSync('historyList', this.historyList);
        // 导航到详情页面,并传递用户ID和用户代码作为参数
        uni.navigateTo({
            url: '/pages/talent/detail?id=' + foundItem.id + '&code=' + foundItem.code
        });
    } else {
        return uni.showToast({
            title: '未找到相关创作者',
            icon: 'none'
        });
    }
    //输入完成后清空搜索框
    this.keyword = '';
},
cleanHistory() {
    uni.showModal({
        content: '是否清除历史记录',
        success: (res) => {
            if (res.confirm) {
                // 清除本地存储中的历史记录数据
                uni.removeStorageSync('historyList');
                //重置数组
                this.historyList = [];
            }
        }
    });
},
navigateBack() {
	//返回上一级页面
    uni.navigateBack();
},
//这一步是为了实现在历史记录中点击数据可以继续转到对应的详细页面
//传入参数item,也就是你在数组里的数据
navigateToDetail(item){
	//将传入的参数赋值给搜索的参数
    this.keyword = item;
    //继续检查此数据是否存在数组、历史记录中,是的话直接跳转到详情页面。
    this.searchAction();
}

无外部文件源版脚本

keyword:'',//默认为空
historyList:[],//数组默认为空
localData: [
	{ id: "1", name: "创作者A", code: "CODE123" },
	{ id: "2", name: "创作者B", code: "CODE456" }
] // 直接在代码中定义数据
onLoad() {
	//在页面加载时,从本地存储中读取历史记录并赋值给historyList。
	//如果本地存储中没有历史记录,则初始化为空数组。
	this.historyList = uni.getStorageSync('historyList') || [];
},

methods代码

searchAction(e) {
	//如果你输入的数据不为空并且不存在于历史记录数组中
	//就在codeSearch方法中新增到数组并将数据放置于最前
	if (this.keyword !== '' && !this.historyList.includes(this.keyword)) {
		this.codeSearch();
		//写这个是因为发现被存入历史记录的数据无法再次进行搜索
		//检查关键词是否在历史记录数组中,在的话就删除此数据(codesearch方法中的初始化数组),重新传入。
	} else if (this.historyList.includes(this.keyword)) {
		this.codeSearch();
    } else {
        return uni.showToast({
        	title: '请输入你要搜索的内容',
        	icon: 'none'
        });
     }
},
async codeSearch() {
	// 显示一个加载提示框,提示用户正在查询中
	uni.showLoading({
		title: '正在查询中...'
	});
	// 使用本地数据进行搜索
	const foundItem = this.localData.find(item => item.code === this.keyword);
	// 隐藏加载提示框
	uni.hideLoading();
	// 如果本地数据存在
	if (foundItem) {
		//在本地数据中查找与用户输入的关键词匹配的项
		this.historyList = [this.keyword, ...this.historyList];
		// 将当前的keyword添加到历史记录列表的最前面
		this.historyList.unshift(this.keyword);
		// 将更新后的历史记录列表保存到本地存储
		uni.setStorageSync('historyList', this.historyList);
		// 导航到详情页面,并传递用户ID和用户代码作为参数
		uni.navigateTo({
			url: '/pages/talent/detail?id=' + foundItem.id + '&code=' + foundItem.code
        });
	} else {//如果失败
		// 显示一个提示框,告知用户查询失败的原因
        return uni.showToast({
        // 使用响应中的消息内容作为提示信息,可以直接写明查询失败的原因
        	title: r.msg,
        	icon: 'none'//不显示图标
        });
    }
    //输入完成后清空搜索框
    this.keyword = '';
},
cleanHistory() {
	uni.showModal({
		content: '是否清除历史记录',
		success: (res) => {
			if (res.confirm) {
				// 清除本地存储中的历史记录数据
				uni.removeStorageSync('historyList');
                //重置数组
                this.historyList = [];
            }
        }
    });
},
navigateBack() {
	//取消搜索操作
	uni.navigateBack();
},
//这一步是为了实现在历史记录中点击数据可以继续转到对应的详细页面
//传入参数item,也就是你在数组里的数据
navigateToDetail(item){
	//将传入的参数赋值给搜索的参数
    this.keyword = item;
    //继续检查此数据是否存在数组、历史记录中,是的话直接跳转到详情页面。
    this.searchAction();
}

最终效果展示(有无外部数据源都一样,只有样式不一样)

搜索后的界面

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值