Home  >  Article  >  Web Front-end  >  vue fuzzy query keyword plus color

vue fuzzy query keyword plus color

WBOY
WBOYOriginal
2023-05-27 17:43:39689browse

Vue is a very popular JavaScript framework. One of its important functions is to allow developers to easily build interactive and dynamic web applications. Vue's fuzzy query function makes searching very convenient and can also help developers improve user experience. This article will mainly introduce the implementation method of adding color to keywords in Vue fuzzy query.

Fuzzy query means that in a data set, by entering certain conditions (such as text, numbers, dates, etc.), the data that matches the conditions can be searched. In Vue, we can use v-model to bind an input box and then search through the computed attribute. The specific implementation is as follows:

<template>
  <div>
    <input type="text" v-model="keyword"/>
    <ul>
      <li v-for="item in filteredData">{{ highlight(item) }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [
        {id: 1, name: 'Apple'},
        {id: 2, name: 'Banana'},
        {id: 3, name: 'Orange'},
        {id: 4, name: 'Watermelon'},
        {id: 5, name: 'Grape'},
      ],
      keyword: ''
    }
  },
  computed: {
    filteredData () {
      return this.data.filter(item => item.name.toLowerCase().includes(this.keyword.toLowerCase()))
    }
  },
  methods: {
    highlight (item) {
      const regex = new RegExp(this.keyword, 'gi')
      return item.name.replace(regex, `<span class="highlight">${this.keyword}</span>`)
    }
  }
}
</script>

<style>
.highlight {
  color: red;
}
</style>

In the above code, we first bind an input box, and then filter the data through the computed attribute in the v-for instruction to filter out the data that matches the keyword. Next, we defined a highlight method, using regular expressions to wrap keywords in HTML tags and add styles. Finally, in the defined style sheet, we set the color for the highlight class.

It should be noted that in order to prevent XSS vulnerabilities, Vue's v-html directive or DOMPurify library should be used to render HTML tags.

In summary, Vue’s fuzzy query function is very convenient, making the search very flexible, and the keyword and color function can further enhance the user experience. The implementation method is also relatively simple, you only need to define a highlight method. Developers can make changes and optimizations according to their needs.

The above is the detailed content of vue fuzzy query keyword plus color. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn