Use Vue3+Vant component to implement App search history function (sample code)

Use Vue3+Vant component to implement App search history function (sample code)

I am currently developing a new app project. This is also my first time developing an app. After a period of research and investigation by the team, we decided to use the Vue3+Vant front-end component model for development. We have used Vue2 for several projects, so we decided to try using Vue3 for front-end development this time.
I just started to be responsible for the development of the search function, and there was a demand for historical search records. At first, I thought that the storage information of this record would also be placed in a database table, but after some investigation, I found that this was not the case, and it had to be stored locally. However, the methods on the Internet did not completely solve the problem. After some attempts, I finally got it done. Without further ado, here are the results.
Initialize the display of search history

Initialize bu and do not display historical search records

Press Enter to search and enter the details page

Press Enter to search and enter the details page

History Page

Press Enter to search and load the history information.

Clear History

Clear History

First, create a js file. This js file mainly includes the functions of adding historical record information and deleting all historical record information.

export default {

  // Add search home page history query record addSearchHistory(state, payload) {
    // When the list contains the record, delete it const index = state.searchHistoryList.indexOf(payload);
    if (index > -1) {
      state.searchHistoryList.splice(index, 1);
    }
    state.searchHistoryList.unshift(payload);
    // The maximum number of records in the history record is 20 const count = state.searchHistoryList.length;
    state.searchHistoryList.splice(20, count);
  },

  // Clear the search history on the home page clearSearchHistory(state) {
    state.searchHistoryList = [];
  },
};

Vue Code Blocks

<template>
  <!-- Search Box -->
  <search-bar
    @searchClick="searchClick"
    :placeholderValue="state.placeholderValue"
    :searchVal="state.searchVal">
  </search-bar>
  <div class="search">

    <!-- Search History -->
    <div class="history" v-if="state.isShowHistory">
      <span class="proHot">Search History</span>
      <span class="delHotSearch" @click="delHostClick">Clear History</span>

      <!-- Store historical record information-->
      <div class="searchBtn-div">
        <span v-for="(item, index) in state.historyList" :key="index" class="searchValBtn" >
        <van-button
          round
          size="small"
          @click="searchValClick(item)"
          >{{ item }}
        </van-button>
      </span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  onMounted,
  reactive,
  getCurrentInstance,
} from 'vue';
import { Toast, Dialog } from 'vant';
import searchBar from '@/components/SearchBar.vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

export default {

  components:
    searchBar,
  },

  setup() {
    const router = useRouter();
    const store = useStore();
    const { proxy } = getCurrentInstance();
    const state = reactive({
      isShowHistory: '', // Whether to display history searchVal: '', // Search keyword placeholderValue: 'Search for products/information/standards/ingredients/enterprises',
      historyList: [], // historical search data});


    // Enter to search const searchClick = (val) => {
      store.commit('addSearchHistory', val);
      // router.push({ path: '/search-detail', query: { searchVal: val } });
    };

    // Clear history const delHostClick = async () => {
      Dialog.confirm({
        message: 'Are you sure you want to delete your search history? ',
      }).then(() => {
        store.commit('clearSearchHistory', store);
        state.isShowHistory = false;
        Toast({
          message: 'Deleted successfully',
          position: 'bottom',
        });
      });
    };
	
	// Initialize and obtain historical search record information onMounted(async () => {
      // Get historical search information state.historyList = store.state.searchHistoryList;
      // Determine whether to initialize the display history search if (state.historyList.length > 0) {
        state.isShowHistory = true;
      } else {
        state.isShowHistory = false;
      }
    });

    return {
      state,
      searchClick,
      delHostClick,
    };
  },
};
</script>

<style lang="less" scoped>
</style>

If you copy and paste the Vue code directly, you may not be able to use it directly, because a lot of business codes have been deleted, and the remaining ones are mainly the codes for historical search records. There are three main focuses:

Introducing useStore

import { useStore } from 'vuex';

const store = useStore();

Initialize search history

// Initialize and obtain historical search record information // Each time this page is loaded, this method will be called first to get the latest information onMounted(async () => {
      // Get historical search information state.historyList = store.state.searchHistoryList;
      // Determine whether to initialize the display history search if (state.historyList.length > 0) {
        state.isShowHistory = true;
      } else {
        state.isShowHistory = false;
      }
    })

The search box triggers a search event and stores the search information in the Store

// The child component emits an event, and the parent component calls const searchClick = (val) => {
    	// Put the search value into the history	
      store.commit('addSearchHistory', val);
      // Route redirection can be ignored // router.push({ path: '/search-detail', query: { searchVal: val } });
    };

Clear History

// Clear history const delHostClick = async () => {
      Dialog.confirm({
        message: 'Are you sure you want to delete your search history? ',
      }).then(() => {
      	// Clear history informationstore.commit('clearSearchHistory', store);
        state.isShowHistory = false;
        Toast({
          message: 'Deleted successfully',
          position: 'bottom',
        });
      });
    };

The above is the details of using Vue3+Vant component to implement the App search history function. For more information about vue search history, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of how to use the Vue license plate input component
  • Vue elementui implements the example code of the search bar public component encapsulation
  • Detailed explanation of the encapsulation and application of Vue2.x general condition search components
  • Vue component practice searchable drop-down box function
  • Implementation code of Vue drop-down menu component (including search)
  • Vue.js project el-input component listens to the enter key to implement the search function example
  • Implementing a custom component for searchable drop-down box based on Vue
  • Vue component implements searchable drop-down box extension
  • Detailed explanation of the use of Vue2.0 multi-condition search component
  • Detailed explanation of how to use the Vue license plate search component

<<:  Open the Windows server port (take port 8080 as an example)

>>:  VMware 15.5 version installation Windows_Server_2008_R2 system tutorial diagram

Recommend

Use of SerialPort module in Node.js

Table of contents Purpose Module Installation Bas...

MySQL5.7 parallel replication principle and implementation

Anyone who has a little knowledge of data operati...

Detailed explanation of the usage of DECIMAL in MySQL data type

Detailed explanation of the usage of DECIMAL in M...

In-depth explanation of the impact of NULL on indexes in MySQL

Preface I have read many blogs and heard many peo...

Tutorial on installing Tomcat server under Windows

1 Download and prepare First, we need to download...

Understanding what Node.js is is so easy

Table of contents Official introduction to Node.j...

iFrame is a great way to use it as a popup layer to cover the background

I have been working on a project recently - Budou ...

How to start a Java program in docker

Create a simple Spring boot web project Use the i...

Comparison of the advantages of vue3 and vue2

Table of contents Advantage 1: Optimization of di...

Graphic tutorial on configuring nginx file server in windows 10 system

Download the Windows version of Nginx from the Ng...

Detailed explanation of how to create an array in JavaScript

Table of contents Creating Arrays in JavaScript U...

A brief analysis of mysql index

A database index is a data structure whose purpos...

Using vue3 to imitate the side message prompt effect of Apple system

Table of contents Animation Preview Other UI Libr...

Tutorial on installing mongodb under linux

MongoDB is cross-platform and can be installed on...