小程序实时监听搜索数据并将关键字高亮显示

2023-11-10

在这里插入图片描述

<template>
  <view>
    <view class="box">
     <view class="search">
     	<image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/mini-wx/images/homeIndex/search.png" mode=""></image>
     	<view class="inputCon">
     		<input type="search"
     		 placeholder="搜索地铁站" 
     			v-model="searchValue"
     			 confirm-type="search"
     			@confirm="search()">
     	</view>
     </view>
	 <view class="list-box" v-if="showList">
	   <view class="item active" v-for="(item, index) in stationList" :key="index" @click="onSelectStation(item)" v-html="item.subway_name">
	   </view>
	 </view>
     <view v-if="isContent">
     	<view style="margin-top: 20rpx;" class="pickers">
     			<picker
     			  :value="multiIndex"
     			  @change="onChange"
     			  @columnchange="onColumnChange"
     			  mode="multiSelector"
     			  :range="multiArray"
     			  range-key="label"
     			>
     			<text>定位</text>
     				<view style="max-width:max-content;
     				height: 46rpx;
     				border-radius: 12rpx 12rpx 12rpx 12rpx;
     				border: 2rpx solid rgba(0,139,124,0.1);
     				padding: 10rpx;">
     						<image src="https://ebk-picture.oss-cn-hangzhou.aliyuncs.com/ebk-wap/img-202304231132081261-Group%2034001.png" mode=""></image>
     						<text style="font-size: 28rpx;
     						font-weight: 400;
     						color: #008B7C;
     						line-height: 33rpx;">{{station}}</text>
     							
     					  </view>
     			  <!-- <view class="picker-value">{{ line }} - {{ station }}</view> -->
     			</picker>
     	</view>
     	<text class="search_txt">历史记录:</text>
     	<view class="search_history">
     	  <view v-for="(item, index) in searchHistory" :key="index" @tap="onSearchHistoryTap(item)" class="search_item" @click="toIndex()">
     	    <text>{{ item }}</text>
     	  </view>
     	</view>
     </view>
      
    </view>
   
  </view>
</template>

<script>
export default {
data() {
  return {
    sub: "",
    multiArray: [],
    multiIndex: [0, 0],
    line: "", 
    station: "",
    lines: [], 
    stations: [] ,
    City:[],
    searchValue:'',
    searchHistory:[],
    stationList: [], // 下拉列表数据
    showList: false ,// 判断下拉列表是否显示
	timer: null ,// 定时器开关
	isContent:true,//出现下拉列表时隐藏页面内容
	zhanshi:""
  };
},
 watch: {
    searchValue: function(val) {
      if (this.timer) clearTimeout(this.timer); // 清除上个定时器
      this.timer = setTimeout(() => {
        if (val) {
          this.search(); // 发起搜索请求
          this.showList = true; // 显示下拉菜单
		  this.isContent = false
        } else {
			this.stationList = []//清空上一次的下拉展示记录
          this.showList = false; // 隐藏下拉菜单
		  this.isContent = true
        }
      }, 300); // 设置定时器,延迟 300 毫秒后开始搜索
    }
  },
 // 在组件挂载后获取 localcityNm 缓存值,并请求地铁线路列表
 mounted() {
   this.sub = uni.getStorageSync("localcityNm");
   this.getSubwayLinesList();
 },
 
 // 在页面加载时获取历史搜索记录和定位标志,将定位标志设为 false
 onLoad(){
   this.searchHistory = uni.getStorageSync("searchHistory")
   console.log(this.searchHistory+'11')
   const isDinwei = uni.getStorageSync('isDinwei')
   uni.setStorageSync('isDinwei',false)
 },
 
 methods: {
   // 跳转到首页
   toIndex(){
     uni.navigateBack(1)
   },
   // 点击历史搜索记录项触发的事件
   onSearchHistoryTap(item) {
	   console.log(item,'我是点击的某一项')
     // 将点击的历史搜索记录项值赋给搜索框
     this.searchValue = item;
     // 执行搜索方法进行搜索,并将定位标志设置为 true
     this.onSelectStation();
	 uni.setStorageSync('localcityNm', this.searchValue); 
     const isDinwei = uni.getStorageSync('isDinwei')
     uni.setStorageSync('isDinwei',true)
   },
// 选择了某个地铁站时,更新当前页面显示的地铁站名称和存储的相关信息
onSelectStation(station) {
  this.station = station.subway_name; // 更新当前显示的地铁站名称
  uni.setStorageSync('localcityNm', station.subway_name); // 存储所选地铁站名称
  const currentStationObj = JSON.parse(JSON.stringify(station));
  const { subway_latitude, subway_longitude } = currentStationObj;
  const newCityData = { lat: subway_latitude, lng: subway_longitude };
  uni.setStorageSync('City', newCityData); // 存储所选地铁站的经纬度信息

  const history = uni.getStorageSync('searchHistory') || [];
   const newStationName = station.subway_name.replace(/<[^>]*>/g, ''); // 去除所有 HTML 标签
  if (!history.includes(newStationName)) {//判断搜索历史记录中是否有值,无值执行以下代码
	  this.searchHistory = history;
	  	this.searchHistory.unshift(newStationName);//在历史记录数组中首位添加搜索内容
	  	  if (this.searchHistory.length > 10) { // 保留10个值
	  		this.searchHistory.pop()//当大于十个值时删掉数组末尾的值
	  	  }
	uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录
    const isDinwei = uni.getStorageSync('isDinwei');
    uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作
    // history.push(newStationName);
	uni.setStorageSync('localcityNm', newStationName);
	this.searchValue = ''
	this.toIndex(); // 跳转到首页
    this.searchHistory = history;
		 uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录
  }else{
	  //有搜索记录,删除之前的旧记录,将新搜索值重新push到数组首位
	  console.log('11111111111111111111111')
	  this.searchHistory = history;
	  let i = this.searchHistory.indexOf(newStationName);
	  this.searchHistory.splice(i, 1);
	  this.searchHistory.unshift(newStationName);
	  if (this.searchHistory.length > 10) { // 保留10个值
	  	this.searchHistory.pop()
	  }
	   uni.setStorageSync('searchHistory', this.searchHistory); // 存储搜索历史记录
	  // 请勿重复搜索
	  this.toIndex(); // 跳转到首页
	 const isDinwei = uni.getStorageSync('isDinwei');
	 uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作
	 uni.setStorageSync('localcityNm', newStationName);
	  uni.setStorageSync('isDinwei', true); // 设置已定位标志为true,避免再次进行定位操作
	  this.searchValue = ''
	  this.isContent = true
	  this.showList = false; // 关闭下拉列表
  }
},
async search() {
  try {
    const res = await this.$request.post("subway/getSubwayStation", {
      city_id: uni.getStorageSync("localcityId"),
      subway_name: this.searchValue.trim()
    });
    const data = res.data;
	// console.log(data,'数据格式')
    const station = data[0];
    if (station) {
		this.showList = true;
		 this.isContent = false
		
		//一定要是大于等于,不然匹配规则就有问题,匹配到单个不会显示
      if (data.length >= 1) {
        // 如果匹配到多个地铁站,则将所有信息保存到stationList中,并显示下拉列表
        this.stationList = data;
		      this.stationList = data.map(item => {
		               const reg = new RegExp(this.searchValue, 'g'); // 使用正则表达式进行全局匹配
		               const newName = item.subway_name.replace(reg, `<span style="color:#008B7C">${this.searchValue}</span>`); // 将匹配到的部分用<span>标签包裹,并修改文字颜色
		               return { ...item, subway_name: newName };
		             });
					 console.log(this.stationList,'我是处理好的数据')
       
      }
	  else {
        // 如果只匹配到一个地铁站,则直接定位到该地铁站
        this.station = station.subway_name;
        uni.setStorageSync('localcityNm', station.subway_name);
        const currentStationObj = JSON.parse(JSON.stringify(station));
        const { subway_latitude, subway_longitude } = currentStationObj;
        const newCityData = { lat: subway_latitude, lng: subway_longitude };
        uni.setStorageSync('City', newCityData);
        const history = uni.getStorageSync('searchHistory') || [];
		 const newStationName = station.subway_name.replace(/<[^>]*>/g, '');
	
   //      if (!history.includes(newStationName)) {
   //        const isDinwei = uni.getStorageSync('isDinwei')
   //        uni.setStorageSync('isDinwei',true)
		 //  this.toIndex()
   //        history.push(newStationName);
		 
		 //  uni.setStorageSync('localcityNm', newStationName);
   //        this.searchHistory=history;
		 
   //        uni.setStorageSync('searchHistory', this.searchHistory);
   //      }
      }
    } else {
		this.showList = false;
		 this.isContent = true
      uni.showToast({
        title: '未找到该地铁站点',
        icon: 'none'
      });
    }
  } catch (error) {
    console.log(error);
  }
},
 
   // 请求地铁线路列表
   async getSubwayLinesList() {
     try {
       const res = await this.$request.post("subway/getSubwayLinesList", {
         city_id: uni.getStorageSync("localcityId")
       });
       const data = res.data;
       const lines = data;
       // 格式化地铁线路名称列表数据,并存储到当前组件实例的 lines 属性中
       this.lines = lines.map(item => ({
         label: item.lines,
         value: item.id
       }));
       this.line = lines[0].lines; // 初始化当前选中的地铁线路名
       this.getSubwayStations(lines[0].id); // 获取第一个地铁线路的站点列表
     } catch (error) {
       console.log(error);
     }
   },
  // 请求指定地铁线路的站点列表
  async getSubwayStations(lineId) {
    try {
      // 调用后端API获取数据
      const res = await this.$request.post("subway/getSubwayStationList", {
        lines_id: lineId
      });
      const data = res.data;
      // 将数据存储到stations变量中
      const stations = data;
      // 将每个站点的名称和id转换为label和value,存储到this.stations数组中
      this.stations = stations.map(item => ({
        label: item.subway_name,
        value: item.id
      })); // 存储地铁站点名称列表到 data 中
      // 将data中的所有数据存储到City变量中
      const City = data
      this.City = City
      // 如果用户没有选择站点,则默认选择距离用户最近的站点
      if (!this.station) {
        // 如果用户还没有选择站点,则将其设为本地存储中的城市名localcityNm
  	  this.station = uni.getStorageSync('localcityNm')
      }
      // 设置选中的站点为当前地铁线路的第一个站点
      this.multiIndex = [this.multiIndex[0], 0];
      // 更新多列选择器的数据源
      this.multiArray = [this.lines, this.stations];
    } catch (error) {
      console.log(error);
    }
  },
  
  // 线路选择器值改变事件
  onChange(e) {
    const that = this;
    // 获取picker选择器中的索引值
    const multiIndex = e.detail.value;
    // 获取当前选中的地铁线路的名称
    const lineName = that.lines[multiIndex[0]].label;
    // 获取当前选中的地铁站点的名称
    const stationName = that.stations[multiIndex[1]].label;
    // 将当前选中的地铁站点的名称存储到本地存储中,用于下次默认选择
    uni.setStorageSync('localcityNm', stationName);
    // 根据当前选中的地铁站点名称获取该站点的经纬度信息,并存储到localStorage中
    const currentStation = that.City.find(item => item.subway_name === stationName);
    if (currentStation) {
      const currentStationObj = JSON.parse(JSON.stringify(currentStation));
      const { subway_latitude, subway_longitude } = currentStationObj;
      const newObj ={lat:subway_latitude, lng:subway_longitude}
      uni.setStorageSync('City', newObj);
    }
    // 更新选中的地铁线路、站点名称
    that.line = lineName;
    that.station = stationName;
    // 重新获取并更新站点列表数据
    that.getSubwayStations(
      that.lines.find(item => item.label === lineName).value
    );
    // 更新多列选择器的数据源和选中的索引值
    that.multiArray = [that.lines, that.stations];
    that.multiIndex = multiIndex;
    // 跳转到首页
    this.toIndex()
    // 设置isDinwei为true,表示已经定位
    const isDinwei = uni.getStorageSync('isDinwei')
    uni.setStorageSync('isDinwei',true)
  },
  
  // 列变化事件
  onColumnChange(e) {
    let that = this
    // 获取列和行的索引值
    const columnIndex = e.detail.column;
    const rowIndex = e.detail.value;
  
    // 如果列变化的是地铁线路列,则重新获取站点列表并更新右侧 picker 列表的数据源
    if (columnIndex === 0) {
      const lineId = that.lines[rowIndex].value;
      that.getSubwayStations(lineId);
    }
  }

}
};
</script>


<style lang="less" scoped>
	.box{
		padding-left:24rpx ;
		padding-right: 20rpx;
		.search_history{
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			.search_item{
				width: max-content;
				height: 56rpx;
				border-radius: 12rpx 12rpx 12rpx 12rpx;
				opacity: 1;
				border: 2rpx solid rgba(0,0,0,0.1);
				margin-right:20rpx ;
				padding-left: 8rpx;
				padding-right: 8rpx;
				margin-bottom: 20rpx;
				text{
					font-size: 28rpx;
					font-weight: 400;
					line-height: 56rpx;
					text-align: center;
					color: #666666;
				}
			}
		}
		.picker {
			  font-size: 16px;
			  color: #000;
			  line-height: 40px;
			  text-align: center;
			  border: 1px solid #ccc;
			  border-radius: 4px;
			  padding: 0 10px;
			  margin-top: 20px;
			}
		.pickers{
			text{
				font-size: 24rpx;
				font-weight: 400;
				color: #666666;
				line-height: 68rpx;
			}
			image{
				width: 24rpx;
								height: 28rpx;
								vertical-align: middle;margin-right: 6rpx;
			}
		}
		.search_txt{
			font-size: 24rpx;
			font-weight: 400;
			color: #666666;
			line-height: 98rpx;
		}
		.search {
					/* // flex: 1; */
					height: 64rpx;
					position: relative;
					background-color: #FFFFFF;
					// bottom: -0rpx;
					border-radius: 300rpx;
					image {
						position: absolute;
						width: 22rpx;
						height: 18rpx;
						top: 22rpx;
						left: 22rpx;
						z-index: 999;
					}
		
					input {
						width: 90%;
						height: 62rpx;
						position: absolute;
						left: 0;
						top: 0;
						margin: 0 auto;
						// border: none;
						background-color: #FFFFFF;
						border: 1rpx solid rgba(0,0,0,0.2);
						border-radius: 300rpx;
						padding: 0;
						margin: 0;
						padding-left: 60rpx;
						color: #666666;
						font-size: 24rpx;
					}
				}
				.dinwei{
					font-size: 24rpx;
					font-weight: 400;
					color: #666666;
					line-height: 28rpx;
				}
	}
	.list-box{
		padding: 22rpx;
		.item{
			width: 100%;
			padding-bottom: 20rpx;
			padding-top: 20rpx;
			border-bottom: 1rpx solid rgba(0,0,0,0.02);
			color: #666666 ;
			font-size: 30rpx;
		}
		.item:hover .active{
			color: #000;
		}
	}
</style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

小程序实时监听搜索数据并将关键字高亮显示 的相关文章

  • java 实体类 临时注解_MyBatis-Plus 常用注解

    TableName TableId 主键专属 比如数据中的表中的字段是id 但是实体类是userId 那么就需要在userId上打上这个注解 用法 设置主键映射 value映射主键字段的名字 type 设置主键类型 主键的生成策略 圈起来的
  • git提交代码完整目录(详细)

    1 找到需要提交的git代码 2 初始化 git init 3 查询状态 git status 4 添加代码 git add test txt test txt是需要提交的文件 git add all 提交所有 5 git文件commit仓
  • DKVMN知识追踪描述

    由于在线学习课程的兴起 学习者在课程学习过程中有很多习题练习的记录 利用这些记录 知识追踪 Knowledge Tracing 希望通过对学习者过往练习的结果分析其当前对一些概念的掌握程度 知识追踪任务可以形式化为一个有监督的序列学习问题
  • eclipse + armgcc + pyocd(CMSIS-DAP) 进行嵌入式MCU Debug

    eclipse armgcc pyocd CMSIS DAP 进行嵌入式MCU Debug 由于中美贸易战的影响 备用方案将采用国产MCU 经过乱开发委员会的评估 认为华大 HDSC 的MCU性价比不错 但是keil官网找不到所选芯片的pd
  • Java thread中对异常的处理策略

    https www cnblogs com googlemeoften p 5769216 html
  • Flutter开发之滚动Widget

    移动端数据量比较大时 我们都是通过列表来进行展示的 比如商品数据 聊天列表 通信录 朋友圈等 在Android中 我们可以使用ListView或RecyclerView来实现 在iOS中 我们可以通过UITableView来实现 在Flut

随机推荐

  • sql中对日期的筛选

    转载自 点击打开链接 几个小时内的数据 DATE SUB NOW INTERVAL 5 HOUR 今天 select from 表名 where to days 时间字段名 to days now 昨天 SELECT FROM 表名 WHE
  • Flutter —— dart基础语法

    Flutter dart基础语法 1 Flutter 项目创建 2 Dart 语法 2 1 var final和const 2 2 num 2 3 string 2 4 list 和 map 2 5 和 2 6 方法 和 箭头函数 2 7
  • 刚面完的字节跳动Python软件测试用例编写(含思路)

    测试用例编写是软件测试的基本技能 也有很多人认为测试用例是软件测试的核心 软件测试中最重要的是设计和生成有效的测试用例 测试用例是测试工作的指导 是软件测试的必须遵守的准则 在这里我们不讨论以上的各种观点 但是综上所述 大家可以看出 测试用
  • QT中的connect用法总结

    第一种 首先来看看老版本的 connect 写法 比较复杂些 需要将信号和槽进行明确的指定 包括形参 看一个示例 为方便演示 先自定义一个 Button 然后定义两个重载的信号 lass MyButton public QWidget Q
  • 仓库 “https://download.docker.com/linux ubuntu Release” 没有 Release 文件。N: 无法安全地用该源进行更新,所以默认禁用该源

    解决 E 仓库 https download docker com linux ubuntu Release 没有 Release 文件 N 无法安全地用该源进行更新 所以默认禁用该源 在ubuntu16 04上安装Docker Engin
  • CentOS 7 修改系统运行级别(单用户/正常启动)

    常用的系统运行级别 3级 带网络多用户命令行界面 multi user target 5级 带网络多用户图像化界面 graphical target 正常启动的系统使用systemctl命令修改运行级别 查看当前运行级别 systemctl
  • [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍

    前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索 Eastmount 关键字及截图的功能 而这篇文章主要简单介绍如何实现自动登录163邮箱 同时继续介绍Selenium Python官网Locating
  • MySQL中的事务

    1 事务介绍 本篇文章我们来介绍数据库中事务的概念以及如何使用MySQL命令行窗口来进行数据库的事务操作 事务是联合操作中我们数据库稳定运作和数据不发生不可预知错误的重要依赖 事务是指数据库中的一组逻辑操作 这个操作的特点就是在该组逻辑中
  • STM32-时钟系统

    1 时钟的定义 时钟是单片机运行的基础 时钟信号推动单片机内各个部分执行相应的指令 时钟系统就是CPU的脉搏 决定cpu速率 像人的心跳一样 只有有了心跳 人才能做其他的事情 而单片机有了时钟 才能够运行执行指令 才能够做其他的处理 点灯
  • 数学建模——BP神经网络学习笔记

    一 BP神经网络简述 人工神经元概述 归纳一下生物神经元传递信息的过程 生物神经元是一个多输入 单输出单元 常用的人工神经元模型可用下图模拟 当神经元j有多个输入xi i 1 2 m 和单个输出yj时 输入和输出的关系可表示为 其中j为阈值
  • 5.4结构型模式—————装饰模式

    装饰模式的定义与特点 装饰 Decorator 模式的定义 指在不改变现有对象结构的情况下 动态地给该对象增加一些职责 即增加其额外功能 的模式 它属于对象结构型模式 装饰 Decorator 模式的主要优点有 采用装饰模式扩展对象的功能比
  • flash读写 STM32G070 HAL库 STM32CubeMX

    flash读写 STM32G070 HAL库 STM32CubeMX 1 程序通过串口写入及读写数据 通过printf打印输出 注 这里不讲解printf 的设置 2 写入数据代码 HAL StatusTypeDef flash write
  • Mybatis————Gitee中检出项目到myeclipse

    1 在gitee中新建仓库 2 在myeclipse中 import git 输入 创建好的 仓库的地址 就是上图中的 克隆 下载 那个地方的地址 然后输入 gitee的用户名密码 点击next 找到你本地的路径 next 导入一个新的ma
  • 高斯过程回归预测Matlab简单实现

    0 说在前面的话 如果是新手入门高斯过程回归的话建议先读这篇博客才能更好理解下面的程序哟 快速入门高斯过程回归预测 1 单点预测例题 主程序 clear close all 求解程序 x 1 5 1 0 75 0 4 0 25 0 输入测量
  • moviepy音视频开发:audio_normalize调整剪辑音量大小到正常

    前往老猿Python博文目录 概述 audio normalize函数用于将一个剪辑的音量大小调整到正常 调整的思路就是将剪辑中音频帧数据的最大值取出来 当其值小于1时 表示剪辑的音量偏小 以1为参考 将所有剪辑帧数据的值都乘以1和剪辑帧数
  • 代码重构与单元测试——测试项目(二)

    二 创建测试项目 我们已经创建了充电宝计费项目 做为我们这次重构的遗留系统 为了验证我们每次重构的正确性 我们需要一个测试项目 对我们重构的代码进行测试 接下来我们来创建这个测试项目 1 在Visual Studio 2019的 解决方案资
  • 解决无法使用gpt的问题

    1 此方法是前提你得有一台服务器之后的操作 2 地区不支持 错误代码1020可以用此方法解决 脚本地址 wget N no check certificate https gitlab com rwkgyg CFwarp raw main
  • 浏览器渲染原理

    浏览器渲染原理 渲染时间点 渲染流水线 解析 HTML Parse HTML 解析 HTML Parse HTML Document Object Model 1 解析 HTML Parse HTML CSS Object Model 解析
  • Eigen 使用碎碎记_norm、normalize、normalized的区别

    本文转载自Eigen中norm normalize normalized的区别 norm normalize normalized的区别 include
  • 小程序实时监听搜索数据并将关键字高亮显示