In VueJs, I am working on retrieving the ID and value of the element that has been clicked in order to successfully submit the data to

In my project, I am working on a feature that involves toggling job offers between visible and invisible using a toggle button. When the page loads, a GET request retrieves the status (true or false) from the database to determine whether the toggle button should be toggled. My goal is to capture the value and ID of the clicked child element so that I can send a request to update the database accordingly (for example, changing from 'invisible' to 'visible' for future page loads).

I have been exploring different approaches, but it seems like I still have some gaps in my understanding. Here is the structure of the parent component:

<template>
  <div class="container">
    <header>
      <navigation-bar role="COMPANY"/>
    </header>

    <main>
      <section class="page-menu">
        <CompanyPageSelectorMenu/>
      </section>

      <section class="job-offers" v-if="jobOffers">
        <div class="scroll" id="scrollbar-styling" v-for="jobOffer of jobOffers" :key="jobOffer.id">
          <CompanyJobOfferList :functionBold="jobOffer.jobFunction" :amount-per-session="jobOffer.amountPerSession" :functionDescription="jobOffer.jobDescription" :isChecked="jobOffer.visible"/>
      </div>
      </section>


    </main>
  </div>
</template>

<script>
  import CompanyPageSelectorMenu from "../components/CompanyPageSelectorMenu.vue";
  import NavigationBar from "../components/NavigationBar";
  import CompanyJobOfferList from "../components/CompanyJobOfferList";
  import axios from 'axios';
  import {Utils} from "../assets/utils";

export default {
name: "CompanyJobOffer",
  components: {NavigationBar, CompanyPageSelectorMenu, CompanyJobOfferList},
  data () {
    return {
      jobOffers: [],
      errors: [],
    }
  },
  created() {
    let userId = Utils.parseJwt(Utils.getCookie("JWT-token")).userId;

    axios.get(`http://localhost:8080/joboffers/` + userId, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${Utils.getCookie("JWT-token")}`
      }
    })
        .then(response => {
          this.jobOffers = response.data
        })
        .catch(e => {
          this.errors.push(e)
        })
  }
}
</script>

Within the parent component, a child component is utilized:

<CompanyJobOfferList :functionBold="jobOffer.jobFunction" :amount-per-session="jobOffer.amountPerSession" :functionDescription="jobOffer.jobDescription" :isChecked="jobOffer.visible"/>

The structure of the child component is as follows:

<template>
  <div class="container">
    <div class="wrap-text">
      <span class="function-text-bold"><b>{{ functionBold }}</b></span>
      <span class="function-text">{{ functionDescription }}</span>
    </div>
    <div class="wrap-text">
      <span class="amount-text">Aantal toegelaten studenten per sessie</span>
      <div class="click-amount">
        <button class="remove-hover"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm6 13h-12v-2h12v2z"/></svg></button>
        <span class="function-text">{{ amountPerSession }}</span>
        <button class="remove-hover"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm6 13h-5v5h-2v-5h-5v-2h5v-5h-2v5h-5v2z"/></svg></button>
      </div>
    </div>
    <button>Stel je tijdslot in</button>
    <!-- Rounded switch -->
    <label class="switch">
      <input type="checkbox" v-if="isChecked" checked="isChecked">
       <input type="checkbox" v-else>
      <span class="slider round"></span>
    </label>
    <hr>
  </div>
</template>

<script>


//import axios from "axios";
export default {
  name: "CompanyJobOfferList",
  data() {
    return {};
  },
  props: {
    functionBold: {
      type: String,
      required: true,
    },
    functionDescription: {
      type: String,
      required: true,
    },
    amountPerSession: {
      type: Number,
      required: true,
    },
    isChecked: {
      type: Boolean,
      required: true,
    },
  },
};
</script>

My challenge lies in obtaining the ID of the clicked component and accessing its current value. Should the POST / PUT request be handled in the child or parent component? The decision between the two depends on factors like the number of child components involved. Initially, I believed sending data to the parent component was the way to go due to multiple child components being present. Despite attempting different methods, I have yet to achieve the desired functionality.

Answer №1

To efficiently communicate between parent and child components, utilize the $emit method. Send an event and id to the child component, then trigger a method on button click. In the parent component:

<CompanyJobOfferList @buttonClicked="handleClick" :id="jobOffer.id">

Create the handle click method in the parent component:

handleClick(arg) {
  // Perform actions using arg
}

In the child component's button:

<button @click="$emit('buttonClicked', id)"></button>

Define props for the child component:

props: {
  id: {
    type: ?,
    required: true
  }
}

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

After reloading the page, Nuxt dynamic routes are displaying a 404 error

Hey there! I'm currently diving into a project that involves using nuxt js, and it's all new to me. I've set it up in spa mode without any modifications in the nuxt config file, just sticking with the default settings. Here's how I&apos ...

Is it possible to link an HTML select element to a changing array in JavaScript?

Let's say I have an empty HTML select element. <select id="options"> </select> Can I link a JavaScript array to this select so that when the array is modified, the select options update accordingly? Alternatively, do I need to resort to ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

Ways to dynamically add a JavaScript file into a webpage

In an attempt to dynamically load a JavaScript file, I utilized a div element with a specific class name to contain the verification script. The script is designed to check if the intended JavaScript file has been loaded and, if not, to generate a new ex ...

An investigation into the texturing and highlighting problem in Three.js

I am currently working on a project involving a cube with multiple textures, one for each face. Initially, I was able to change the color of the cube when hovering over it using a single texture. However, I now want to implement this functionality with a t ...

Modifying the nested data organization in Sequelize

I'm looking to adjust the data structure retrieved from an ORM query involving four tables. The product and category tables have a many-to-many relationship, with the product_category table serving as a bridge. Additionally, there's a fourth tabl ...

The connection between React-redux @connect is malfunctioning, whereas using connect() functions smoothly

Is there an issue with using the @connect() syntax instead of export default connect()? It seems that when I stick to the traditional syntax class PhonePage extends Component { ... } export default connect(state => ({ testedByPhone: state.pho ...

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

Utilizing Functions within Arrays and Exploring Time Intervals for Optimization

I am currently working on a game development project where the game involves answering questions within a specific time frame. Each question should be answered within 10 seconds before resetting for the next one. I'm fairly new to JavaScript and would ...

Troubles with retrieving Array data for a JavaScript column chart

I am currently developing a Flask app in Python and utilizing render_template to send back 2 arrays, "names" and "deals", to my HTML file. I have confirmed that these arrays are working correctly based on the code snippet below that I tested, which display ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

I want to show error messages using jquery only when the username or password is entered incorrectly. How can this be achieved?

document.getElementById("buttonClick").addEventListener("click", mouseOverClick); function mouseOverClick(){ document.getElementById("buttonClick").style.color = "blue"; } $("#buttonClick").hover(function() { $(this).css('cursor',&apos ...

JavaScript code to always keep the element on top of the page: "Make

I have developed a straightforward chrome extension tool that displays a small text message (a div with z-index 999999) on the webpage that the user is currently viewing. However, I am facing a problem where the div sometimes gets hidden beneath the existi ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

Exploring Vue 3.3: Understanding Generics and Dynamic Properties

I'm currently diving into the generics feature in vue 3.3 and I've been pondering about defining the type of an incoming prop based on another prop value. This is my current component structure: export interface OptionProps { id: string | numb ...

How to Determine the Length of a Subarray in JavaScript

I am working with a JSON element that contains nested arrays: json = [ { "category": "Electronic", "param": "param1", "subMenu": [ { "subCategory": "Audio & Hifi", ...

Change the height of a div element using animation upon the button being clicked

I'm attempting to create an animation where a drop-down menu div expands from 0 to 250px in height when the menu button is clicked. I have been using jQuery for this purpose. Here is the relevant section of my HTML code: <script src="https://aja ...

Retrieving checkbox list values using jQuery

I am working with a div that contains some checkboxes. I want to write code so that when a button is clicked, it will retrieve the names of all the checked checkboxes. Can you provide guidance on how to achieve this? <div id="MyDiv"> .... <td> ...

What steps can I take to establish a simple yet secure password authentication using next.js, mongoDB, and bcrypt?

As a hobby programmer working on my project, I aim to implement a secure password authentication system in my next.js project using only my next.js backend API and MongoDB (Atlas via Data API). I understand that there are various third-party authentication ...

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...