本文实例为大家分享了Vue实现搜索结果高亮显示关键字的具体代码,供大家参考,具体内容如下
1. 需要解决的问题
- 父组件将搜索的字段传到子组件
- 子组件接受数据,正则匹配,并替换字段
2. 具体代码
父组件代码
<template> <div> <div v-if="showMe"> <div class="re_search"> <svg @click="$router.go(-1)"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#arrow-left.6f6409e" rel="external nofollow" ></use> </svg> <input type="search" v-model="search_text" class="v-md" placeholder="请输入商品名称" @keydown.enter="search_method"> </div> <OneBusiness v-for="(item, n) in search_res" :key="n" :item="item" :search_text="search_text"></OneBusiness> </div> <!--<!– 撑开Fixednav挡住的位置 –>--> <div class="space"></div> <!-- 固定导航栏 --> </div> </template> <script> import { mapGetters } from 'vuex'; import OneBusiness from './small_components/One_business'; import {getSearchData} from 'src/service/getData' export default { name: 'search', data () { return { showMe: false, search_text: '', // 搜索框内容 search_res: [] // 搜索结果 }; }, mounted () { this.$store.dispatch('setLoading', true); // 模拟加载 var time = Math.floor(Math.random() * 2000); console.log('模拟加载用时' + time); setTimeout(() => { this.$store.dispatch('setLoading', false); this.showMe = true; }, time); this.search_method(); }, computed: { ...mapGetters([ 'getFalseBussinessbrief' // 商家简略信息 ]) }, methods: { async search_method () { var mainWord = this.$route.params.keyword; if (this.search_text !== '' && this.search_text !== this.$route.params.keyword) { mainWord = this.search_text; } this.search_text = mainWord; this.search_res = (await getSearchData(this.search_text)).obj.results; console.log(this.search_res); } }, components: { OneBusiness } }; </script> <style lang="less" scoped> .re_search{ background:#0096ff; line-height:0; padding: .2rem; svg{ width:.6rem; height:.6rem; } input[type="search"]{ display:inline-block; height:.9rem; width:8rem; outline: none; border: none; border-radius:.45rem; background:#f2f2f2; box-sizing: border-box; padding: 0 .5rem; font-size:.4rem; } } </style>
子组件代码
<template> <!-- 列表单个商家 --> <section class="tj_business" > <section class="one_business clear"> <div class="business_img"> <img src="/UploadFiles/2021-04-02/guozhao.png">以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。