Modify the content of a separate division by selecting a different item in a list with the help of Vue.js and TypeScript

I am still learning Vue and may not have all the answers. Currently, I am working on a feature that changes the text of another div based on the item I select from a list. You can find the code sandbox link below along with my current implementation.

Code Sandbox Link: https://codesandbox.io/s/vuetify-ts-mod-forked-5fbvd

<template>
  <div>
    <v-menu bottom left>
      <template v-slot:activator="{ on }">
        <v-btn text class="align-self-center mr-4" v-on="on">
          {{ item.car }} <----this is failing, should match the item I selected in the menu
          <v-icon small class="pl-3">fa-caret-down</v-icon>
        </v-btn>
      </template>

      <v-list class="lighten-3">
        <v-list-item
          v-for="(item, index) in cars"
          :key="index"
          @click="addItem(item)"
        >
          {{ item.car }}
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component
export default class Dropdown extends Vue {
  public cars: any[] = [
    { id: 2, car: "GZ", configs: null },
    { id: 3, car: "AB", configs: null },
    { id: 5, car: "C4", configs: null },
    { id: 1, car: "PA", configs: null },
  ];

  public addItem(item): void {
    console.log("item==========", item);
  }
}
</script>

Answer №1

Make sure to include the currentItem property and update it when you click on a list item inside the addItem method:

<template>
  <div>
    <v-menu bottom left>
      <template v-slot:activator="{ on }">
        <v-btn v-if="currentItem" text class="align-self-center mr-4" v-on="on">
          {{ currentItem.car }} 
          <v-icon small class="pl-3">fa-caret-down</v-icon>
        </v-btn>
      </template>

      <v-list class="lighten-3">
        <v-list-item
          v-for="(item, index) in cars"
          :key="index"
          @click="addItem(item)"
        >
          {{ item.car }}
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component
export default class Dropdown extends Vue {
  public currentItem: any = null
  public cars: any[] = [
    { id: 2, car: "GZ", configs: null },
    { id: 3, car: "AB", configs: null },
    { id: 5, car: "C4", configs: null },
    { id: 1, car: "PA", configs: null },
  ];

  public addItem(item): void {
   this.currentItem = item
  }
}
</script>

Answer №2

The initial item.car is placed outside the for loop, therefore preventing access to the item.

Update the initial item.car to selectedItem.car.

Include a data function in your component:

data () {
    return {
        selectedItem: { car : '' }
    }
}

Modify your addItem function to:

addItem (item) {
    this.selectedItem = item
}

This essentially assigns the selected item to a reactive component data property that can be accessed by your first div.

Please note that the code above is not TypeScript code, but it conveys the idea effectively.

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 with optional generic in Typescript union not functioning as intended

I am facing a challenge with a type that requires an optional generic. In my case, if the generic G is provided, a new property of type G must be included. However, I encountered an issue while trying to implement this in a function: interface Message { ...

Having trouble resetting a checked checkbox label in Vuejs?

uncheck: function(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, uncheckall: function(event) { this.checkedNames = []; }, checkedInput(event) { if (this.checkedNames.includes(event.targ ...

Guide to setting up a hit counter in the MEAN stack framework

QUERY: Is there a way to track the number of hits on each post by a user? I want the count to increase for every unique visitor who sees the post. While I can update and save the count on the server side, how can I restrict it by IP address and prevent ...

I'm keen on utilizing Vue locally, however, it seems to be not functioning properly

In my index.html file, I have the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Title</title> </head> <body> <script type="module"> import Vue ...

Evaluation of jQuery code

Just starting out with jQuery and programming in general. I posted my first hour of work here and would appreciate some feedback on how to improve it. $(function() { function hideElements() //Hides specified elements on page load. { $("li.credentia ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Error message "Undefined is not a constructor" can occur when using Ionic2 with Karma and Jasmine

I'm facing a challenge while trying to create tests for an Ionic2 App using Karma + Jasmine. I encountered a runtime error and, given my lack of experience, I'm having trouble pinpointing the actual issue. Here is my setup: test.ts This file con ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

How to programmatically close an Angular 5 Modal

In my current project, I am working with Angular 5. One of the functionalities I have implemented is a modal window. The HTML structure for this modal looks like this: <div class="add-popup modal fade" #noteModal id="noteModal" tabindex="-1" role="dia ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

What is the method for passing the Rating field value in Vue.js?

Here is the structure of my form: <form id="enquiryBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);"> <div class="modal-body brbottom-20"> <div class="clearfix"> < ...

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...