< vue + ElementUi 组件封装:实现弹窗展示富文本数据,允许全文搜索高亮显示搜索内容 >
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                
<template>
  <el-dialog
    title="富文本内容"
    :visible="visible"
    @close="$emit('update:visible', false)"
  >
    <div v-html="highlightedContent"></div>
    <div slot="footer" class="dialog-footer">
      <el-input
        v-model="searchText"
        placeholder="搜索"
        @input="highlightSearchText"
      ></el-input>
    </div>
  </el-dialog>
</template>
 
<script>
export default {
  props: {
    content: String,
    visible: Boolean
  },
  data() {
    return {
      searchText: '',
      highlightedContent: this.content
    };
  },
  methods: {
    highlightSearchText() {
      if (this.searchText) {
        // 使用正则表达式和replace方法进行搜索和高亮显示
        const highlighted = this.content.replace(new RegExp(this.searchText, 'gi'), match => {
          return `<span style="background-color: yellow;">${match}</span>`;
        });
        this.highlightedContent = highlighted;
      } else {
        this.highlightedContent = this.content;
      }
    }
  }
};
</script>这个代码实例展示了如何在Vue组件中封装一个弹窗,该弹窗可以展示富文本内容,并且允许用户进行全文搜索。搜索时,搜索词会通过正则表达式高亮显示,从而提高可读性。这个例子简洁明了,并且使用了Vue的原理之一:数据绑定和响应式更新。
评论已关闭