Guide to building a personalized dropdown menu with user input using Ant Design Vue and Vue 3

I'm trying to implement a customized dropdown using antdv, but the example provided in the documentation () doesn't cover how to do it based on user input.

Here's my attempt: https://codesandbox.io/s/custom-dropdown-ant-design-vue-3-2-14-forked-3zm0i7?file=/src/demo.vue. However, I am facing difficulties when trying to input a value. If I use

@mousedown="e => e.preventDefault()"
in the div element, then I lose access to the a-input. On the other hand, if I remove it, the a-input disappears before I can type anything. In case you're unable to visit the link, here is the code snippet:


<template>
  <a-select
    v-model:value="value"
    style="width: 120px"
    :options="items.map((item) => ({ value: item }))"
  >
    <template #dropdownRender="{ menuNode: menu }">
      <v-nodes :vnodes="menu" />
      <a-divider style="margin: 4px 0" />
      <!-- <div
        style="padding: 4px 8px;"
        @mousedown="e => e.preventDefault()"
      > -->
      <a-input
        placeholder="add name"
        @mousedown="(e) => e.preventDefault()"
        @change="addItem"
      />
      <!-- </div> -->
    </template>
  </a-select>
</template>

<script>
import { defineComponent, ref } from "vue";

let index = 0;
export default defineComponent({
  components: {
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
  },
  setup() {
    const items = ref(["jack", "lucy"]);
    const value = ref("lucy");

    const addItem = (name) => {
      console.log("addItem");
      items.value.push(name);
    };
    return {
      items,
      value,
      addItem,
    };
  },
});
</script>

Answer №1

To have control over the opening and closing of the select, include the prop :open. You will need to replicate the standard behavior by using @click: open=true, @change: open=false. This way, it won't automatically close when you click on your input field.

I recommend triggering addItem only on @keypress.enter instead of @change to avoid unnecessary calls to addItem with every keypress.

Check out the updated sandbox here

<a-select
  v-model:value="value"
  style="width: 120px"
  :options="items.map((item) => ({ value: item }))"
  :open="open"
  @click="open = true"
  @change="open = false"
>
  <template #dropdownRender="{ menuNode: menu }">
    <v-nodes :vnodes="menu" />
    <a-divider style="margin: 4px 0" />
    <a-input
      v-model:value="inputVal"
      placeholder="add name"
      @keypress.enter="addItem()"
    />
  </template>
</a-select>
setup() {
  const items = ref(["jack", "lucy"]);
  const value = ref("lucy");
  const inputVal = ref("");
  const open = ref(false);

  const addItem = () => {
    items.value.push(inputVal.value);
    inputVal.value = "";
  };
  return {
    items,
    value,
    addItem,
    inputVal,
    open,
  };
}

Answer №2

You are overriding the default behavior of the <a> tag. Consider moving the 'preventDefault()' function inside 'addItem' and utilize @focus instead.

<a-input
        placeholder="add name"
        @focus="e => e.preventDefault()"
        @change="addItem"
      />
const addItem = (e) => {
      e.preventDefault();
      console.log("addItem");
      items.value.push(e.target.value);
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue accessing member value in inherited class constructor in Typescript

My situation involves a class named A, with another class named B that is inherited from it. class A { constructor(){ this.init(); } init(){} } class B extends A { private myMember = {value:1}; constructor(){ super(); ...

The AJAX request for JSON data is functioning correctly in Firefox, but is experiencing compatibility issues with other web browsers

I recently completed a PHP page that generates a valid JSON document. The jQuery code used to fetch and display the data is quite straightforward: $.ajax({ url: "http://localhost:8888/rkm/json-jc", dataType: "json", success: function(data) { ...

filtering the properties of mongoose documents

I have created a schema as shown below: var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: { type: String, required: true }, p ...

Navigating errors during the distribution of numerous messages with SendGrid and Node.js

I have developed a command line application that interacts with a DynamoDB table to extract email addresses for items that have not yet received an email. The process involves creating customized message objects, sending emails using SendGrid's sgMail ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

Using a variable as a key for a JavaScript object literal with a string value

Is there a way to achieve this? objPrefix = btn.attr('data-objprefix'); //<button data-objPrefix="foo"> var sendData = {objPrefix : {"bar":"ccccc"}}; My desired outcome is {"foo" : {"bar":"ccccc"}}; however, the current result shows { ...

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

The onClick event function is activated when the component is first rendered on the screen

Below is the function in my component: myFunc = () => {...} This is how I implemented it: <MyComponent onClick={this.myFunc()}/> The onClick function will trigger when the component mounts. However, if I use either of these alternatives: < ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

Is there a way to successfully implement mouseover/mouseout functionalities while also resizing?

I've been working on a dropdown menu that functions well on both mobile and desktop devices. However, I have encountered an issue with resizing. Even when the screen size is reduced to mobile dimensions, the mouseover and mouseout functions continue t ...

What causes the delay in CSS animations?

Is there a way to trigger an "updating" image to spin while a long JavaScript function is running? I am currently using JQuery to add a class called "spinning", defined in my CSS for the animation. The problem is that when I add the class and then call a l ...

Learning how to utilize getDerivedStateFromProps over componentWillReceiveProps in React

To address a deprecated error, I am looking to update my code from using componentWillReceiveProps to getDerivedStateFromProps. The component is being passed a date prop, and whenever this date changes, the getList function needs to be run with the new dat ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

Transferring chosen string data from <childComponent1/> to <childComponent2/> in vue.js

In my code, I have a block of Vue.js code that involves a <select> element within the <oneChildComponent />: new Vue({ template:' <select v-model="selectedOption" @change="handleChange"> < ...

Creating repeatable texture patterns in Three.js

Hello, I have developed a basic renderer for my 3D objects that are generated using PHP. While I am able to successfully render all the objects, I am facing some major issues with textures. Currently, the texture I am using is sized at 512x512 pixels. I ...

Executing a Cron Job several times daily, each and every day

This is my current code snippet: const CronJob = require('cron').CronJob; new CronJob({ cursoronTime: '* * * * *', // every minute onTick: async function() { console.log(&ap ...

Ensuring the safety of JavaScript requests made to a Web Service

In my project, there is a page that triggers a JSon script when a button is clicked. This script interacts with a web service. To ensure security, the code behind the page generates a script containing an object with a unique code. This code is then added ...

Unable to submit form with Jquery

Having some trouble with my form submission using Jquery. The submit part of my code seems to be malfunctioning, and I can't pinpoint the issue. <?php if(!isset($_SESSION["useridentity"])){ die(header("Location:index.php")); } ...