search
HomeWeb Front-endVue.jsHow to use Vue to implement a JD.com-like search page?

How to use Vue to implement a JD.com-like search page?

Jun 25, 2023 am 09:05 AM
vueJingdongsearch page

Vue is one of the most popular front-end frameworks today. It can help us quickly build efficient and beautiful user interfaces. In this article, we will introduce how to use Vue to implement a JD.com-like search page.

First, we need to prepare the following tools and technologies:

  • Vue CLI: used to quickly initialize a Vue project.
  • axios: used to send HTTP requests and process responses.
  • Vuex: Used to manage the state of the application.
  • Element UI: used to provide various UI components.
  1. Initialize Vue project

It is very simple to initialize a new project using Vue CLI. You only need to execute the following command on the command line:

vue create jd-search

This command will create a project named jd-search in the current directory and automatically install the required dependencies.

  1. Add Element UI

Installing Element UI is very simple, just execute the following command in the command line:

npm install element-ui

After the installation is completed, Introduce Element UI in main.js:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)
  1. Create search component

Create it in the src/components directory A component named Search.vue. This component contains an input box and a search button. The code is as follows:

<template>
  <div class="search">
    <el-input
      v-model="keyword"
      placeholder="请输入关键词"
      class="search-input"
      @keyup.enter.native="search"
    />
    <el-button
      type="primary"
      icon="el-icon-search"
      class="search-btn"
      @click="search"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
    }
  },
  methods: {
    search() {
      this.$emit('search', this.keyword);
    }
  },
}
</script>

<style scoped>
.search {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.search-input {
  width: 500px;
  margin-right: 20px;
}

.search-btn {
  width: 80px;
}
</style>

This component contains a keyword data attribute, which is used to save the keywords entered by the user. When the user clicks the search button or presses the Enter key, the search method will be triggered, passing the current keyword value as a parameter to the parent component.

  1. Create a product list component

Create a component named ProductList.vue in the src/components directory. This component will display the product list of the search results. The code is as follows:

<template>
  <div class="product-list">
    <el-card v-for="product in products" :key="product.id">
      <div slot="header" class="product-header">
        <h3 id="product-title">{{ product.title }}</h3>
        <span class="product-price">{{ product.price }}</span>
      </div>
      <div>
        <img  class="product-image lazy"  src="/static/imghwm/default1.png"  data-src="product.image"  : / alt="How to use Vue to implement a JD.com-like search page?" >
      </div>
      <div>
        {{ product.description }}
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  props: {
    products: {
      type: Array,
      default: () => [],
    },
  },
}
</script>

<style scoped>
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  grid-gap: 20px;
}

.product-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.product-price {
  font-size: 18px;
}
</style>

This component receives an attribute named products, which is used to display the search results. It uses Element UI's el-card and el-image components to display the product list, and uses CSS Grid to implement adaptive layout.

  1. Create a state management module

It is very convenient to use Vuex to manage the status of an application. Create a module named search.js in the src/store directory. This module contains the following states, operations, and getters:

const state = {
  keyword: '',
  products: [],
};

const mutations = {
  updateKeyword(state, keyword) {
    state.keyword = keyword;
  },
  updateProducts(state, products) {
    state.products = products;
  },
};

const actions = {
  async search({ commit }, keyword) {
    const response = await this.$axios.get('/api/search', {
      params: { keyword },
    });
    commit('updateProducts', response.data);
  },
};

const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};

This module contains an asynchronous operation named search that is used to send search requests and update search results. It also contains a state named keyword and a state named products to save the keywords and search results entered by the user.

  1. Create a search page

Create a page named SearchPage.vue, which will contain Search and ProductList components and manage the interaction between them through Vuex. The code is as follows:

<template>
  <div class="search-page">
    <search @search="search" />
    <product-list :products="products" />
  </div>
</template>

<script>
import Search from '@/components/Search';
import ProductList from '@/components/ProductList';
import { mapState, mapActions } from 'vuex';

export default {
  components: { Search, ProductList },
  computed: {
    ...mapState('search', ['products']),
  },
  methods: {
    ...mapActions('search', ['search']),
  },
}
</script>

<style scoped>
.search-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
</style>

This page contains Search and ProductList components, and uses Vuex's mapState and mapActions mapping products attributes and search operations. When the user enters a keyword and clicks the search button or presses the Enter key, the search operation is triggered, the search results are obtained from the backend API, and the products status in Vuex is updated.

  1. Send search request

Configure Axios in src/main.js, the code is as follows:

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

axios.defaults.baseURL = 'http://localhost:3000'

This configuration makes We can use the $axios object in our application to send HTTP requests. Now we can send search requests in the search action.

So far, we have completed the implementation of the JD.com-like search page. This page uses technologies such as Vue, Element UI, Axios, and Vuex, and follows best practices for modern single-page applications.

The above is the detailed content of How to use Vue to implement a JD.com-like search page?. 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
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor