Is there a way for me to activate the button upon clicking on a box in the list?

I found my inspiration from the following sources:

Below is how my vue component looks like:

<template>
    ...
        <b-card-group deck v-for="row in formattedItems">
            <b-card :title="item.title"
                    img-src="http://placehold.it/140?text=No image"
                    img-alt="Img"
                    img-top
                    v-for="item in row">
                <p class="card-text">
                    {{item.price}}
                </p>
                <p class="card-text">
                    {{item.country}}
                </p>
                <div slot="footer">
                    <b-button-group size="sm">
                        <b-button :pressed.sync="oriPress" variant="outline-primary">Original</b-button>
                        <b-button :pressed.sync="kwPress" variant="outline-primary">Kw</b-button>
                    </b-button-group>
                    <b-btn variant="primary" block>Add</b-btn>
                </div>
            </b-card>
        </b-card-group>
    ....
</template>

<script>
    export default {
        ..
        data () {
            return{
                items: [
                     {id:1, title:'chelsea', price:900, country: 'england'},
                     {id:2, title:'liverpool', price:800, country: 'england'},
                     {id:3, title:'mu', price:700, country: 'england'},
                     {id:4, title:'city', price:600, country: 'england'},
                     {id:5, title:'arsenal', price:500, country: 'england'},
                     {id:6, title:'tottenham', price:400, country: 'england'},
                     {id:7, title:'juventus', price:300, country: 'italy'},
                     {id:8, title:'madrid', price:200, country: 'span'},
                     {id:9, title:'barcelona', price:100, country: 'span'},
                     {id:10, title:'psg', price:50, country: 'france'}
                ],
                oriPress: true,
                kwPress: false
            }
        },
        mounted: function () {
            this.getItems()
        },
        computed: {
            formattedItems() {
                return this.items.reduce((c, n, i) => {
                    if (i % 4 === 0) c.push([]);
                    c[c.length - 1].push(n);
                    return c;
                }, []);
            }
        }
    }
</script>

Upon execution of the script, all original buttons are active and all kw buttons are inactive by default.

However, I encounter an issue where clicking either the kw or original button makes all buttons active or inactive. My desired functionality is to only activate the selected button within each box when clicked.

For instance, if there are 10 boxes, clicking the original button in the third box should only activate that button while deactivating the kw button. The same behavior should apply for other boxes as well.

How can I achieve this specific behavior?

Answer №1

In order to address the issue, it's important to note that the current implementation uses the same oriPress and kwPress data properties for all items. To make these unique to each item, consider moving those properties into the individual objects within the items[] array:

// script
data() {
  return {
    items: [
      {id: 1, oriPress: true, kwPress: false, ...},
      {id: 2, oriPress: true, kwPress: false, ...},
    ]
  }
}

//template
<b-card-group v-for="row in formattedItems">
  <b-card v-for="item in row">

      <b-button :pressed.sync="item.oriPress">Original</b-button>
      <b-button :pressed.sync="item.kwPress">Kw</b-button>

  </b-card>
</b-card-group>

If modifying the shape of items[] is not feasible, an alternative approach is to create separate maps for oriPress and kwPress properties, one for each item. This can be achieved by using a watcher on the items[] array to initialize the maps:

// script
data() {
  return {
    items: [...],
    oriPress: {},
    kwPress: {},
  }
},
watch: {
  items: {
    immediate: true,
    handler(value) {
      this.oriPress = value.reduce((p,c) => {
        p[c.id] = true;
        return p;
      }, {});

      this.kwPress = value.reduce((p,c) => {
        p[c.id] = false;
        return p;
      }, {});
    }
  }
},


//template
<b-card-group v-for="row in formattedItems">
  <b-card v-for="item in row">

      <b-button :pressed.sync="oriPress[item.id]">Original</b-button>
      <b-button :pressed.sync="kwPress[item.id]">Kw</b-button>

  </b-card>
</b-card-group>

new Vue({
  el: '#app',
  data() {
    return{
      items: [
        {id:1, title:'chelsea', price:900, country: 'england'},
        {id:2, title:'liverpool', price:800, country: 'england'},
        {id:3, title:'mu', price:700, country: 'england'},
        {id:4, title:'city', price:600, country: 'england'},
        {id:5, title:'arsenal', price:500, country: 'england'},
        {id:6, title:'tottenham', price:400, country: 'england'},
        {id:7, title:'juventus', price:300, country: 'italy'},
        {id:8, title:'madrid', price:200, country: 'span'},
        {id:9, title:'barcelona', price:100, country: 'span'},
        {id:10, title:'psg', price:50, country: 'france'}
      ],
      oriPress: {},
      kwPress: {}
    }
  },
  watch: {
    items: {
      immediate: true,
      handler(value) {
        this.oriPress = value.reduce((p,c) => {
          p[c.id] = true;
          return p;
        }, {});
        this.kwPress = value.reduce((p,c) => {
          p[c.id] = false;
          return p;
        }, {});
      }
    }
  },
  computed: {
    formattedItems() {
      return this.items.reduce((c, n, i) => {
        if (i % 4 === 0) c.push([]);
        c[c.length - 1].push(n);
        return c;
      }, []);
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a782f0ecf7ecf3f5">[email protected]</a>"></script>

<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/>
<script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>

<div id="app">
  <b-card-group deck v-for="row in formattedItems">
    <b-card :title="item.title"
            img-src="http://placehold.it/140?text=No image"
            img-alt="Img"
            img-top
            v-for="item in row">
      <p class="card-text">
        {{item.price}}
      </p>
      <p class="card-text">
        {{item.country}}
      </p>
      <div slot="footer">
        <b-button-group size="sm">
          <b-button :pressed.sync="oriPress[item.id]" variant="outline-primary">Original</b-button>
          <b-button :pressed.sync="kwPress[item.id]" variant="outline-primary">Kw</b-button>
        </b-button-group>
        <b-btn variant="primary" block>Add</b-btn>
      </div>
    </b-card>
  </b-card-group>
</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

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Encountered an error: Vue is not recognized within Laravel environment

While working on a Laravel application with Vue 3, I encountered an issue. When trying to load the welcome.blade.php file, I couldn't see the Vue file content and received the following error in the console: Uncaught ReferenceError: Vue is not defined ...

"Embracing Micro-frontends: Building dynamic web applications using a variety of frontend

I am currently facing a software architecture dilemma. My extensive monolithic web application is built using PHP and backbone js, but I am eager to integrate a new front-end framework like react/vue. The question arises about the best approach to tackle t ...

"Troubleshooting issue: No response received when uploading files in VueJs3 with Laravel 8

Seeking assistance with a persistent issue that I have been unable to resolve despite trying various methods. Your help would be greatly appreciated. Below is my Vue template for creating categories: <form @submit.prevent="createCat" enctype= ...

Send the id of the chosen row to the Component tag within the blade file

I'm working on passing the id of the currently selected row within a for loop when it's clicked on. The goal is to then pass that id to a Vue component. In my index.blade file: @foreach($cats as $cat) <tr> <td class="catme" d ...

Trouble with Bootstrap accordion staying open even after a different one is chosen

Looking for assistance! I am encountering an issue with using jQuery on Bootstrap. The accordion feature is not functioning correctly as it fails to collapse when another section is selected. https://i.stack.imgur.com/uiZPh.png The problem arises when th ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

Prevent WordPress themes from running in order to integrate a personalized Vue.js front-end application

I'm currently working on a basic website that will utilize vuejs as the front-end framework and wordpress for generating dynamic content. To achieve this, I've placed wordpress inside the public directory of my vue project in a folder named app. ...

Issues with displaying AJAX Bootstrap Modals

I'm struggling to display a Bootstrap modal with dynamically generated content from the database. The data is not showing up in the modal body, and I've been troubleshooting this issue for quite some time now. Modal <div class="modal fade" i ...

The Vuejs code functions properly in the overall application, but is not functioning within the specific component

Before, my Vue.js app worked flawlessly until I tried putting it into a Vue component. It started throwing the following error: [Vue warn]: Error compiling template. Here's the code for the component (components.php): <script> Vue.component(&ap ...

Utilizing jQuery UI progress bar to monitor lengthy PHP operations

I've been working on enhancing Thunderbird's chat log archives with a custom chat log manager. The manager includes a synchronization feature that processes the log files, uploads messages to a database, zips the logs, and saves them in an archiv ...

Creating an Interactive Form with Laravel and Vue.js to Store and Modify Database Entries

Can someone help me with creating a simple input box that fetches the default value from a database and updates the database when the user changes the value? I am working on a project using Laravel 5.5 and Vue components. The initial value should be retrie ...

Redirecting in Laravel after making an AJAX request results in a "Method Not Allowed" error

I've encountered an unusual problem with my web application built using Vue 3 and Inertia, which includes forms. So, here's the scenario: If I have two browsers open and log out in one, then trigger an Ajax request in the other, it goes through t ...

Vue Websockets twofold

I am experiencing some issues with Laravel/Echo websockets and Vue.js integration. I have set up everything as required, and it works, but not quite as expected. The problem arises when I refresh the page and send a request - it displays fine. However, if ...

Exploring the endless possibilities of using repeatable bootstrap panels

The current code structure is as follows (custom wells, labeled as well-xxxx, apply brand colors to default wells): <div class="panel-group" id="accordion1"> <div class="panel panel-info"> <div class="panel-heading" data-toggle="colla ...

Please refrain from displaying the user table data in the View page source under any script tags

When I access the user data in the script tag of my app.blade.php file, the page resources show this line of code. 'window.user = {"id":2,"name":"test","email":"hidden_email@example.com","email_verified_at":null,"created_at":"2021-03-02T04:52:43.0000 ...

Using PHP to submit a file through an API

I'm currently working on creating an API endpoint to integrate with my Laravel and Vue application. public function avatar(Request $request) { $user = User::find(Auth::id()); $validator = Validator::make($request->all(), [ ...

Deleting a database query once the modal is closed

When visiting the artist's about page on my website, clicking on the "button" will open a modal that retrieves information from a database. Currently, when you click on one artist button, close the modal, and then click on another artist, both artists ...

The information transmitted from the Laravel controller is not syncing with the Vue variable as expected

I've been working on a web app with a dashboard using Laravel and Vue. While passing data from the controller to the Vue file, the data is received correctly. However, when I try to set it to a Vue variable, the value does not update in the variable. ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...