Home > Web Front-end > Front-end Q&A > How to implement search history in vue

How to implement search history in vue

PHPz
Release: 2023-04-18 15:10:52
Original
1995 people have browsed it

In today's era of rapid technological development, search has become an indispensable function in our daily lives. Behind the search engine, the search history of one user after another is often hidden, so that users can better manage their search records and find the information they need faster. In this article, we will introduce how to use Vue to implement the search history function.

1. Prerequisite knowledge

Before we start, we need to master a certain amount of Vue knowledge. Of course, for beginners, this article is also a good practice project.

Specifically, we need to know how to use Vue components, how to use Vuex state management library, and how to use localStorage and other basic concepts and methods.

2. Project Description

The search history function we will implement mainly includes the implementation of the following three aspects:

1. Input box search function: in the input box After entering the keyword, click the search button to search.

2. Search history function: Store the search records performed by the user in localStorage, so that the user can quickly find the history records the next time he searches.

3. History record management function: Users can operate history records, such as clearing history records, deleting a certain history record, etc.

3. Project implementation

1. Create Vue component

We first create a Search component, which is responsible for the specific implementation of the search history function.

<template>
    <div>
        <input type="text" v-model="keyword">
        <button @click="handleSearch">搜索</button>
        <ul>
            <li v-for="(item, index) in searchHistory" :key="index">
                {{item}}
                <span @click="handleDelete(index)">删除</span>
            </li>
        </ul>
        <button @click="handleClear">清空</button>
    </div>
</template>
Copy after login

Here we include an input box, a search button and a list showing history records. Among them, the v-model instruction is used to implement two-way data binding and bind the keyword keyword in the input box; the v-for instruction is used to cyclically display the history record list.

2. Create Vuex state management

Vuex can be understood as a global state management mechanism. When data communication needs to be carried out between multiple components, we can use Vuex to achieve it. Here, we need to use Vuex to save and update the search history.

//store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        searchHistory: []
    },
    mutations: {
        addSearchHistory(state, keyword) {
            if (!state.searchHistory.includes(keyword)) {
                state.searchHistory.push(keyword)
                localStorage.setItem('searchHistory', JSON.stringify(state.searchHistory))
            }
        },
        clearSearchHistory(state) {
            state.searchHistory = []
            localStorage.removeItem('searchHistory')
        },
        deleteSearchHistory(state, index) {
            state.searchHistory.splice(index, 1)
            localStorage.setItem('searchHistory', JSON.stringify(state.searchHistory))
        },
        initSearchHistory(state) {
            state.searchHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]')
        }
    },
    getters: {
        searchHistory(state) {
            return state.searchHistory
        }
    }
})
Copy after login

In the store.js file, we define the relevant content of Vuex state management. In state, we define the search history array searchHistory, and in mutations we define operations such as adding, deleting, and clearing the array, and we also perform operations on localStorage. The initSearchHistory is used to initialize the array. When there is a history record in the browser, it should be initialized before creating the component.

3. Page implementation

Next, we need to connect the Search component with Vuex state management so that it has corresponding functions. Here, we need to focus on the methods part of the component.

<script>
import {mapActions, mapGetters} from 'vuex'

export default {
    name: 'Search',
    data() {
        return {
            keyword: ''
        }
    },
    computed: mapGetters({
        searchHistory: 'searchHistory'
    }),
    methods: {
        ...mapActions([
            'addSearchHistory',
            'clearSearchHistory',
            'deleteSearchHistory',
            'initSearchHistory'
        ]),
        handleSearch() {
            if (this.keyword) {
                this.addSearchHistory(this.keyword)
                // do search
            }
        },
        handleClear() {
            this.clearSearchHistory()
        },
        handleDelete(index) {
            this.deleteSearchHistory(index)
        }
    },
    created() {
        this.initSearchHistory()
    }
}
</script>
Copy after login

In the methods section, we first map searchHistory to the component through mapGetters. Next, we map the corresponding operations in the Vuex state to the component through mapActions, which includes the add, delete, clear, and initialization operations we defined previously. In the specific implementation, when we click the search button, we need to add the keywords in the input box to the search history and search at the same time.

4. Summary

Based on the above operations, we can already implement the search history function. This article implements the keyword search function, the saving and updating of historical records, and the management functions of historical records. Through the study of this small project, we can better master the operation methods of Vue components, Vuex state management library and localStorage.

Other points worth reminding are that for some complex applications, LocalStorage may not be a good choice because it can only store string types, which may cause type confusion; at the same time, in relatively complex use cases Next, Vuex also needs corresponding optimization strategies to improve performance. In use, we need to flexibly choose the appropriate method to meet the needs of front-end development.

The above is the detailed content of How to implement search history in vue. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template