Basic idea:

1. How do I render strings with HTML tags in Vue?

<div v-html="htmlStr"></div>

data () {
  return {
    htmlStr: 'Hello <span style="color: red">World</span>'
  }
}
Copy the code

  1. How do I replace specified characters in a string with highlighted (HTML wrapped) characters? SRC/views/search/components/search – suggess. Lenovo vue search Suggestions

    <template> <div class="search-suggess"> <van-cell icon="search" v-for="(text,index) in searchList" :key="index" @click="$emit('search',text)"> <! <div slot="title" V-html ="lightHeight(text)"></div> </van-cell> </div> </template> // LightHeight (text) {const hilightSearchStr = '<span class="active">${this.searchText}</span>' // const hilightSearchStr = '<span class="active">${this.searchText}</span> Reg = new RegExp(this.searchText, 'ig') // Regular expression return text.replace(reg, <style scoped lang="less">. Search-suggess {/deep/ span. Active {color: purple; } } </style>Copy the code

Front-end complete code:

<template> <div class="search-suggess"> <van-cell icon="search" v-for="(text,index) in searchList" :key="index" @click="$emit('search',text)"> <! <div slot="title" V-html ="lightHeight(text)"></div> </van-cell> </div> </template> <script> import { getSearchSuggessions } from '@/api/search' import { debounce } from 'lodash' export default { name: "SearchSuggess", // The child suggess receives data from the parent component props: {searchText: {type: String, required: True}}, data() {return {searchList: [] // search for associative result data}}, // child component to listen for changes in the parent component's search box content: {searchText: {// console.log(value) // this.loadSearchsuggess (value) // call the search request //}, handler: debounce(function (value) { // console.log(value) this.loadSearchSuggess(value) }, 200), immediate: True // This callback will be called immediately after listening starts}}, methods: {// article suggess async loadSearchess (q) {try {const {data} = await getSearchSuggessions(q) // console.log(data); This. SearchList = data.data.options} catch (error) {this.$toast(' failed to get data, try again later ')}}, LightHeight (text) {const hilightSearchStr = '<span class="active">${this.searchText}</span>' // highlight characters Const reg = new RegExp(this.searchText, 'ig') // Regular expression return text.replace(reg, HilightSearchStr) // Replace with highlighted characters}}} </script> <style scoped lang="less">. Search-suggess {/deep/ span. Active {color: purple; } } </style>Copy the code