search
HomeWeb Front-endFront-end Q&AVue drop-down box asynchronously requests to pass value

Vue is a front-end framework. The advantage of using it is that you can easily build complex single-page applications. In Vue, the drop-down box is one of the commonly used form components. In some scenarios where dynamic loading of options is required, data needs to be requested asynchronously and passed to the drop-down box to achieve functional integrity. This article will introduce the use of the Vue framework to implement the value transfer method after the drop-down box asynchronously requests data.

1. Demand scenario

In actual applications, the options in the drop-down box are dynamically loaded, and an asynchronous request needs to be made to the server to obtain data. For example, in an e-commerce website, all product categories need to be displayed in a drop-down box, and the product categories change dynamically. In order to avoid repeated transmission of large amounts of data, it is necessary to use asynchronous requests to obtain product categories and pass their values ​​to the drop-down box.

2. Data binding

Data binding in Vue is implemented through the v-model directive. v-model can implement two-way data binding, so that user input and page data are updated synchronously. Therefore, you first need to define a data object in the Vue instance and bind it to the v-model directive of the drop-down box to achieve the delivery of options.

For example, in the following code, we create a data object named "categories" and bind it to the v-model directive of the drop-down box. The selected value will be updated in real time to "categories" and vice versa.

<template>
  <select v-model="categories">
    <option v-for="category in categoriesList" :value="category.id">{{ category.name }}</option>
  </select>
</template>

<script>
export default {
  data() {
    return {
      categories: null, // 定义categories数据对象
      categoriesList: [] // 定义categoriesList数据对象,存放异步请求获取的选项数据
    };
  }
};
</script>

3. Asynchronous request data

Next step, we need to initiate an asynchronous request to obtain the option data of the drop-down box. Generally speaking, asynchronous requests need to be executed in Vue's life cycle function, usually in the "created" or "mounted" function. Here we use the axios library to initiate network requests.

For example, in the following code, we initiate an asynchronous request in the "mounted" function to obtain all product categories and save them in the "categoriesList" array. The data in this array will provide data for the options in the drop-down box.

<template>
  <select v-model="categories">
    <option v-for="category in categoriesList" :value="category.id">{{ category.name }}</option>
  </select>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      categories: null,
      categoriesList: []
    };
  },
  mounted() {
    axios
      .get("http://example.com/categories") // 发起异步请求
      .then(response => {
        this.categoriesList = response.data; // 获取到数据后将其赋值给categoriesList
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

4. Complete code

So far, we have implemented the asynchronous request value passing function of the drop-down box. Below is the complete code, which you can copy into your project for testing.

<template>
  <select v-model="categories">
    <option v-for="category in categoriesList" :value="category.id">{{ category.name }}</option>
  </select>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      categories: null,
      categoriesList: []
    };
  },
  mounted() {
    axios
      .get("http://example.com/categories")
      .then(response => {
        this.categoriesList = response.data;
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

5. Summary

The above example tells us that in Vue, data binding of the drop-down box component is achieved by defining data objects and using the v-model directive. To dynamically load options, we use the "mounted" function to make an asynchronous request, get the data and save it in an array, and finally render the data in the array into the dropdown box.

In practical applications, we can expand the above method as needed, for example, we can add text prompts, search functions, etc. to achieve a more flexible drop-down box function.

The above is the detailed content of Vue drop-down box asynchronously requests to pass value. 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
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool