Home Web Front-end Vue.js Vue component practice: search box component development

Vue component practice: search box component development

Nov 24, 2023 am 09:31 AM
vue components search bar

Vue component practice: search box component development

Vue component practice: search box component development

With the development of the Internet, search functions are becoming more and more common in various applications. In order to facilitate users to quickly query information, the search box has become a standard feature of every website. In this article, we will develop a search box component through Vue.js.

Our search box component needs to have the following functions:

  1. The input box can respond to user input in real time and search when the user inputs;
  2. Users can click to enter Use the search button on the right side of the box to search;
  3. Users can see the search results below the search box.

In order to implement this component, we need to perform the following steps:

  1. Install Vue.js and axios library

Before starting to write the component , we need to install Vue.js and axios libraries first. Vue.js is a progressive framework for building user interfaces, and axios is a library for sending HTTP requests. Both need to be installed through npm. Enter the following command in the terminal to install:

npm install vue axios --save
Copy after login
  1. Create components

We quickly build a Vue project through Vue CLI and create a SearchBox in the src/components directory .vue file, which is our search box component.

  1. Writing the SearchBox.vue component

In the SearchBox.vue file, we need to declare the component and define the template, data, methods, etc. in the component. The following is a simple SearchBox.vue code example:

<template>
  <div class="search-box">
    <input type="text" v-model="searchText" @input="search" />
    <button @click="search">搜索</button>
    <ul>
      <li v-for="result in searchResults" :key="result.id">{{ result.title }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'SearchBox',
  data() {
    return {
      searchText: '',
      searchResults: [],
    };
  },
  methods: {
    search() {
      axios
        .get('https://jsonplaceholder.typicode.com/posts', {
          params: { title: this.searchText },
        })
        .then((response) => {
          this.searchResults = response.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
};
</script>

<style scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #eaeaea;
  padding: 10px;
  border-radius: 5px;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  padding: 5px;
}
</style>
Copy after login

In the above code, we first create a search-box div in the template and place an input box and a search button in it. We bind the value of the input box to the searchText attribute through v-model. When the value of the input box changes, the value of searchText will also change accordingly.

We will call the search method when the user enters content and clicks the search button. In the search method, we use the axios library to send an HTTP request and request the backend interface to obtain data. In this example, we use the virtual API provided by JSONPlaceholder. The content entered by the user will be passed to the interface as query parameters, and the results returned by the query will be displayed in the ul below.

Finally, we also use the scoped attribute to define the scope for the style of the SearchBox component to prevent the style from affecting other components.

  1. Using the SearchBox component in the parent component

Now that we have completed writing the SearchBox component, let’s see how to use it in the parent component. In the parent component, we simply reference the component and pass in the required properties. For example:

<template>
  <div class="app">
    <SearchBox />
  </div>
</template>

<script>
import SearchBox from '@/components/SearchBox.vue';

export default {
  components: {
    SearchBox,
  },
};
</script>

<style>
.app {
  margin: 20px;
}
</style>
Copy after login

In the above code, we introduced the SearchBox component and registered it as a component in the parent component. Styles can be set via

.

So far, we have successfully implemented a simple search box component. When the user enters a search keyword, we will query the corresponding data from the back-end interface and display the query results to the user in real time.

Conclusion

Vue.js is one of the most popular front-end frameworks at the moment. Its component-based programming features allow us to develop various complex applications more efficiently and conveniently. In this article, we implemented a search box component through Vue.js. By instantiating the component and communicating with the parent-child component, we implemented two-way binding of data, invocation of methods, and triggering of events. Master these basic Vue.js knowledge, and I believe you have basically mastered how to develop a simple Vue component.

The above is the detailed content of Vue component practice: search box component development. For more information, please follow other related articles on the PHP Chinese website!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles