VueJs - Dynamic select menu

Hello, I am currently working on implementing a dropdown feature on my website using Vue. As a newcomer to Vue, I am using conditional rendering to display different sets of cards based on user selection. For example, the dropdown options include Cars, Motos, and Bikes. When a user clicks on "Cars," a list of cars is displayed in the dropdown, and similarly for the other options.

 <h2 class="text-center my-font text-light"><button v-on:click="toggle = !toggle" class="badge badge-danger menu-label-size w-50">Cars</button></h2> 
   <div v-if="toggle" class="row">
      <div class="col-12">
         <div class="cards-item text-center ">
            <div v-for="item in cars" ::key="item.id" class="card" style="width: 10rem;">
               <img :src="'./images/cars/img' + item.img + '.png'" class="card-img-top img-fluid" alt="item.name">
               <div class="card-body d-flex flex-column justify-content-end">
                  <h4 class="card-title my-font">{{ item.name }}</h4>
                  <p class="badge-danger font-weight-bold">{{ item.price }}</p>
               </div>
            </div>
         </div>
      </div>
   </div>

   <h2 class="text-center my-font text-light"><button v-on:click="toggle = !toggle" class="badge badge-danger menu-label-size w-50">Motos</button></h2> 
   <div v-if="toggle" class="row">
      <div class="col-12">
         <div class="cards-item text-center">
            <div v-for="item in motos" ::key="item.id" class="card" style="width: 10rem;">
               <img :src="'./images/motos/img' + item.img + '.png'" class="card-img-top img-fluid" alt="item.name">
               <div class="card-body d-flex flex-column justify-content-end">
                  <h4 class="card-title my-font">{{ item.name }}</h4>
                  <p class="badge-danger font-weight-bold">{{ item.price }}</p>
               </div>
            </div>
         </div>
      </div>
   </div>

   <h2 class="text-center my-font text-light"><button v-on:click="toggle = !toggle" class="badge badge-danger menu-label-size w-50">Bikes</button></h2> 
   <div v-if="toggle" class="row">
      <div class="col-12">
         <div class="cards-item text-center">
            <div v-for="item in bikes" ::key="item.id" class="card" style="width: 10rem;">
               <img :src="'./images/bikes/img' + item.img + '.png'" class="card-img-top img-fluid" alt="item.name">
               <div class="card-body d-flex flex-column justify-content-end">
                  <h4 class="card-title my-font">{{ item.name }}</h4>
                  <p class="badge-danger font-weight-bold">{{ item.price }}</p>
               </div>
            </div>
         </div>
      </div>
   </div>

My script:

const app = new Vue({
el: '#app',
data: {
    show: false,
    cars: [{data}],
    motos: [{data}],
    bikes: [{data}],
},
})

However, when clicking on "Motos," it only closes the "Cars" dropdown. How can I make it dynamic so that when "Motos" is clicked, it opens while "Cars" closes, and vice versa for "Bikes"?

Answer №1

In the mounted hook of your Vue component, you can consolidate and merge data for different types of vehicles. Afterwards, you can iterate through these items to display them:

const app = new Vue({
  el: '#demo',
  data: () => ({
    items: [],
    expanded: null,
    cars: [{img: '', name: 'car1', price: 5}, {img: '', name: 'car2', price: 6}, {img: '', name: 'car3', price: 8}],
    motors: [{img: '', name: 'motor1', price: 5}, {img: '', name: 'motor2', price: 6}, {img: '', name: 'motor3', price: 8}],
    bikes: [{img: '', name: 'bike1', price: 5}, {img: '', name: 'bike2', price: 6}, {img: '', name: 'bike3', price: 8}]
  }),
  methods: {
    expand(idx) {
      this.expanded = this.expanded === idx ?  null : idx
    }
  },
  mounted() {
    const car = {title: 'Cars', products: this.cars}
    const motor = {title: 'Motors', products: this.motors}
    const bike = {title: 'Bikes', products: this.bikes}
    this.items = [car, motor, bike]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3d30302b2c2b2b22e393936">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1BaDx" crossorigin="anonymous">
<div id="demo" class="d-flex">
  <div v-for="(group, index) in items" :key="index">
    <h2 class="text-center my-font text-light">
      <button @click="expand(group)" class="badge badge-danger menu-label-">{{ group.title }}</button>
    </h2>
    <div class="row">
      <div class="col-12">
        <div class="cards-item text-center">
          <div v-if="expanded === group">
            <div v-for="(item, idx) in group.products" :key="idx" class="card" style="width: 10rem;">
              <img :src="'./images/motos/img' + item.img + '.png'" class="card-img-top img-fluid" :alt="item.name">
              <div class="card-body d-flex flex-column justify-content-end">
                <h4 class="card-title my-font">{{ item.name }}</h4>
                <p class="badge-danger font-weight-bold">{{ item.price }}</p>
              </div>
            </div>
           </div>
        </div>
      </div>
    </div>
  </div>
</div>

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

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...

Switching camera view on mouse click with three.js

I am new to three.js and apologize if my question is a bit complex. I have set up my scene in three.js but now I want the camera's position to smoothly transition from point A to point B (which I will specify in my code). I plan on using Tween.js to ...

Unable to add text to texarea using jquery

I recently discovered and am experimenting with smiley and uikit to create a feature that allows users to insert emoticons into a textarea. Here is the HTML structure: <textarea class="smiley-input uk-width-1-1"></textarea> <button type= ...

A step-by-step guide on Implementing a Getter/Setter on an Object

Is there a way to apply a getter/setter directly to an object when defining it? For instance, if I want to have myobj = 123 trigger console.log(123) I am aware that it can be done using class extends, but I am interested in a simpler method that incorpo ...

Executing numerous GET requests with varying parameters in AngularJS

Update: My apologies to those who answered, it turns out that the code was correct, but requests were being intercepted and losing all parameters. I am attempting to send repeated HTTP GET requests to a REST API based on the response, using the solution I ...

What methods can I use to toggle between different divs using navigation buttons?

There are 4 divs on my webpage that I need to toggle between using the up and down arrows. Despite trying an if else statement, it doesn't work as intended. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.c ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

Using a Get request may not retrieve the most recent data that was added through a Post request

I've added some data using a Post request and now I'm trying to retrieve all the data from the table using a Get request. However, it seems that the last data I added is not being included in the response. Is there a specific approach I should ta ...

Creating a Vue.js directive that can access the context of a loop

Vue.directive("custom", { inserted(el, binding, vnode) { let val = binding.value; let arg = binding.arg let mods = binding.modifiers let expr = binding.expression let cont = vnode.context .... // adjust l ...

Error encountered: The Bootstrap modal() function is showing as undefined when using npm modules

Every time I attempt to call $("#myDiv").modal(), an error occurs. The error message reads: Uncaught TypeError: undefined is not a function This error has popped up in different scenarios, with various parameters being passed to modal(). Many solutions o ...

Developed a query, seeking information for populating a dropdown menu

I am currently in the process of editing a webpage that utilizes both PHP and HTML. Essentially, I have a dynamic list of items being generated where the number of values can vary based on the row length. Next to each item in the list, there is a "delete ...

Exploring the world of DOM manipulation in AJAX websites?

Hello everyone, I am fairly new to developing extensions but I am eager to learn. I am currently working on creating an extension that specifically blocks certain Twitter icons. Through a helpful tutorial, I have been able to gather a lot of information. I ...

What is the best way to configure Winston with Webpack?

I'm working on an electron application that utilizes node.js and I want to integrate the Winston logging library. After adding Winston to my package.json file, I encountered warnings from the colors.js dependency when running the webpack build command ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

I'm looking to achieve a horizontal wrapping alignment of cards in Vuetify 2. How can I accomplish this?

In my current project using vuetify 2, I am facing an issue where all my cards are displaying vertically within a col of width 7 instead of in a horizontal overflow. My goal is to have the cards arranged vertically with five counts on each row, and any ov ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Can you help identify the issue in this particular ajax code?

Here is the code I wrote to check if a username exists in the database using Ajax. However, I am facing an issue where the input text from the HTML page is not being sent to the checkusername.php file via $_POST['uname'];. I have tried multiple s ...

Unable to include Buefy or Bulma in a Vuejs project

I am working on a Vue.js project and I would like to incorporate the Bulma framework and possibly Buefy as well. To start, I used the commands npm install bulma and npm install buefy In the main.js file, my setup looks like this: import Buefy from &apos ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

JavaScript TypeError - missing method issue

When I try to call this code, I am encountering a TypeError: player = new Player({name:''}); Player = MeteorModel.extend({ schema:{ name:{type:String,}, value:{} }, belongsTo:{ meteorCollection:'', methodName ...