Steps for passing a prop to a child component when clicked in Vue2

The intention of this code is to activate a child component when clicking on it within a parent Vue.

Parent Vue file:

<PackageItem
  v-for="pack in packagesData"
  :key="pack.id"
  @click.native="selectPackageItem(pack.id, pack.humanLabel, pack.humanPrice, pack.index)"
>

Child component:

props: {
  selected: Boolean
},

data () {
  return {
    selected: selected
  }
},

How can I pass the selected prop to a child component on click? Instead of setting it like this:

<PackageItem
  :selected="true"
  @click.native="selectPackageItem(pack.id, pack.humanLabel, pack.humanPrice, pack.index)"
>

This would set all items to be selected as true, but I only want to do it on click.

Answer №1

If you wish to achieve this functionality:

<PackageItem
  v-for="pack in packagesData"
  :key="pack.id"
  @click.native="
    selectPackageItem(pack.id, pack.humanLabel, pack.humanPrice, pack.index)"
  :selected="selected[pack.id]"
>

Simply utilize the selectPackageItem method to designate the selected package:

selectPackageItem(packId, packLabel, packPrice, packIndex) {
    this.$set('selected', packId, true)

Alternatively, if you want a toggle effect between true and false upon click:

this.$set('selected', packId, !this.selected[packId])

For the data option, keep it simple with:

selected: []

Note that the extra code in your child component is unnecessary:

/* REMOVE
 data () {
   return {
     selected: selected
   }
 },
*/

To access selected props within script, use this.selected, while inside the template simply refer to selected.

Answer №2

To take control of the selection process from the parent component, you can create an array to store selected ids and a function to check if an id is already selected.

data(){
    return {
        ...
        selected: []
    }
},
methods: {
    isSelected(id){
        return this.selected.indexOf(id) > -1;
    }
}

In your click method, simply add or remove the clicked item's id in the array.

// Placeholder for `selectPackageItem` method
if(this.isSelected(id)){
    // Option to deselect
} else {
    this.selected.push(id);
}

Now, your template will look like this:

<PackageItem v-for="pack in packagesData" :selected="isSelected(pack.id)" :key="pack.id" @click.native="selectPackageItem(pack.id, pack.humanLabel, pack.humanPrice, pack.index)">

Answer №3

After some brainstorming, I devised a more polished solution:

<PackageItem
  v-for="pack in packagesData"
  :key="pack.id"
  :selected="isSelectedPackage(pack.index)"
  @click.native="selectPackageItem(pack.id, pack.humanLabel, pack.humanPrice, pack.index)"
>

I also implemented a method to validate selected packages stored in an array:

isSelectedPackage (index) {
  let packages = this.packages
  let isSelected = packages.some(p => p.index === index)
  return isSelected
}

The function isSelectedPackage outputs a boolean value. The variable this.packages holds an array of active packages that were clicked, each containing detailed information alongside the ID and index. By using .some, I compare the clicked item's index with those in the array (this.packages) to determine if they match.

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

Troubleshooting sound problems in Angular JS

Can anyone help with pausing an AngularJS audio when the browser window is closed and resuming it when the window is maximized? I'm new to AngularJS and have no idea how to achieve this. var app=angular.module("myApp",['ngAudio']); ...

Changing the opacity of the background when a Bootstrap modal is displayedHere's how you can

While working with a bootstrap modal, I noticed that the background content opacity does not change by default when the modal is open. I attempted to change this using JavaScript: function showModal() { document.getElementById("pageContent").style.opaci ...

Angular checkboxes not triggering ng-click event

Within my Angular application, there is a form that includes checkbox inputs: <div ng-repeat="partner in type.partners"> <label class="checkbox-inline"> <input type="checkbox" value="partner" ng-checked="report.participa ...

What is the best way to eliminate the hash from the URL of a single-route Angular application without the need for ui.router?

I came across a question that has been asked before on Stack Overflow, but unfortunately, it remains unanswered and without any comments. In my Angular app, I am working with a single route and I want to find a way to eliminate the # from the URL. If I h ...

`Optimizing Performance using jQuery Functions and AJAX`

As someone exploring ajax for the first time, I'm eager to learn how to write jQuery code that ensures my simple functions like slideshows and overlays still work smoothly when a page is loaded via ajax. Currently, I am implementing the following met ...

Dealing with jQuery hover disruption while toggling classes

I have a simple script below where I want to change the background color on hover for different buttons (regular/inactive and active) and toggle between the two states upon clicking. Although the code successfully changes the background color during hover ...

Encountering mixed content error on webpack development server

My React based website is currently running on Cloud9 using webpack-dev-server, which serves content over https. However, I have encountered an issue when attempting to make ajax (network) requests to external http links. The error message I receive is: ...

JavaScript module dependency management technique

Just starting out with JavaScript, I'm attempting to incorporate a JavaScript library/sdk. I've familiarized myself with common patterns and currently considering using the revealing module pattern. To provide a concrete example, let's imagi ...

Turn the camera to focus on the chosen object using three.js

I've been working on designing a map and I'm trying to achieve a specific functionality. When I select any geometry, I want the object to be positioned at the center of the viewport with the camera looking directly at it. Despite searching extens ...

Employing the Vuetify validation feature for ensuring the accuracy of text input through manual

In my Vuetify web application, there is a search box that triggers validation rules when the user hits the search icon. If the input does not meet the regex specs, an error message is displayed. After validating the input, I perform a post request to chec ...

Duplicate the Date object without retaining previous data

Struggling with creating a custom deep clone feature that's encountering issues with the Date object. For instance, let now = {time: new Date()} or let now = {data: new Date().getDay()}. When attempting to copy it, the goal is not to replicate the cur ...

How can one stop users from navigating away from a webpage using the back button on their browser?

1) I'm currently exploring options to display a confirm pop-up when a user tries to leave a page using the browser's back button. It seems that the unload event does not trigger in this scenario. My application is built using angular2. I have att ...

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

Efficiently loading images into a navigation flyout: the ultimate guide

I have a large navigation flyout menu that includes images to display the items. Although it is functioning properly, I have noticed that the page load time is a bit slow due to the higher number of images being loaded. Here is an example of my code: &l ...

Tips for resolving issues with this end-to-end test

Issue arises when clicking on the "Add Rule" button as new "Search Term" and "Search textarea" fields are generated, but Protractor is unable to detect them. describe('Checking for two rules and search terms on "Add New Audience Rule" page', () ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

Transferring SQL server dates to jQuery Calendar through AJAX communication

I am currently working on implementing a jQuery calendar example, and I want to load the dates from my SQL database instead of using hardcoded values. I am considering using Ajax post to send a request to my web method and retrieve the data. However, I am ...

Defining an empty multidimensional array involves declaring a variable that can store

I am working on a Vue.js project and need to implement a multidimensional array model Here is a Fiddle with my code: In my Vue.js data, I have defined an array like this: new Vue({ el: '#app', data: { message: 'Hello Vue.js!' ...

Update with the string before it in a JSON list

Within a JSON file, I came across an array that requires the 'TODO' placeholder to be replaced with the entry above it. To elaborate, the initial "TODO" should be substituted with "Previous question" and the subsequent one with "Next question". ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...