搜索内容高亮

<template>
  <section class="memo-list__content-item">
    <!-- 概要 -->
    <section class="item-title">
      <SearchContent :searchValue="searchValue" :content="item.title" />
    </section>
    <!-- 内容 -->
    <section class="item-content">
      <SearchContent :searchValue="searchValue" :content="item.content" />
    </section>
  </section>
</template>
<script setup lang="tsx">
  // 使用JSX创建组件
  const SearchContent = defineComponent({
    name: 'SearchContent',
    props: {
      searchValue: {
        type: String,
        default: ''
      },
      content: {
        type: String,
        default: ''
      }
    },
    setup (props) {
      const searchValue = props.searchValue
      const content = props.content
      const index = content.indexOf(searchValue)

      if (index === -1) return content

      const searchIndex = searchValue.length + index

      // 搜索结果
      const extraContent = startIndex => (
        <>
          {startIndex ? <span>...</span> : ''}
          <span>{content.slice(startIndex, index)}</span>
          <span style='background: #fae086'>{content.slice(index, searchIndex)}</span>
          <span>{content.slice(searchIndex)}</span>
        </>
      )
      if (searchIndex > CONTENT_CUT_LENGTH) return extraContent(index - 4)
      return extraContent(0)
    }
  })
</script>

你可能感兴趣的:(javascript,jsx,vue3)