vue搜索框输入关键字高亮

先上效果图;

实现效果

vue代码的实现

<template>
  <div style="width: 100%">
    <div style="width:90%;margin:0 auto;">
      <div>
        <el-form :inline="true" :model="formInline">
          <el-form-item label="关键字">
            <el-input v-model="formInline.keyword" clearable @clear="clear"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="clear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 添加标签,样式需要用到v-html指令 -->
      <div v-html="content"></div>
    </div>
  </div>
</template>

JavaScript代码实现部分

<script>
export default {
  name: "ColumnPage",
  data() {
    return {
      formInline: {
        keyword: "",
      },
      content: `<div>二月二,龙抬头。
        暮色里,小镇名叫泥瓶巷的僻静地方,有位孤苦伶仃的清瘦少年,此时他正按照习俗,一手持蜡烛,一手持桃枝,照耀房梁、墙壁、木床等处,用桃枝敲敲打打,试图借此驱赶蛇蝎、蜈蚣等,嘴里念念有词,
        是这座小镇祖祖辈辈传下来的老话:二月二,烛照梁,桃打墙,人间蛇虫无处藏。少年姓陈,名平安,爹娘早逝。
        小镇的瓷器极负盛名,本朝开国以来,就担当起“奉诏监烧献陵祭器”的重任,有朝廷官员常年驻扎此地,监理官窑事务。无依无靠的少年,很早就当起了烧瓷的窑匠,起先只能做些杂事粗活,
        跟着一个脾气糟糕的半路师傅,辛苦熬了几年,刚刚琢磨到一点烧瓷的门道,结果世事无常,小镇突然失去了官窑造办这张护身符,小镇周边数十座形若卧龙的窑炉,一夜之间全部被官府勒令关闭熄火。
        陈平安放下新折的那根桃枝,吹灭蜡烛,走出屋子后,坐在台阶上,仰头望去,星空璀璨。</div>`,
    };
  },
  mounted() {},
  methods: {
    clear() {
      this.publicFn("clear");
      this.formInline.keyword = "";
    },
    onSubmit() {
      if (this.formInline.keyword.length !== 0) {
        this.publicFn("submit");
      }
    },
    publicFn(name) {
      let textC = this.content;
      let reg = new RegExp("</?span.*?>", "gi");
      this.content = this.content.replace(reg, "");
      let regStr = new RegExp(this.formInline.keyword, "gi");
      let arr = textC.match(regStr);
      let index = -1;
      if (name === "submit") {
        // 搜索内容
        textC = textC.replace(regStr, () => {
          index++;
          return `<span style="color:red;font-size: 20px;">${arr[index]}</span>`
        });
        this.content = textC;
      } else {
        // 清空输入内容
        textC = textC.replace(regStr, () => {
          index++;
          return arr[index];
        });
      }
    },
  },
};
</script>

代码写的不是很好,只是自己想到的小功能,写了个大概,有很多想不到的问题、漏洞,欢迎提出意见,建议,感谢;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值