Using Vue.js to dynamically toggle CSS classes based on data using a method

Here is the code snippet I am working with:

<template>
<div id="projects">
  <Header />
  <b-container>
    <div class="row">
      <div :class="colSize" v-for="(data, index) in projects" :key="data._id">
        <b-card :title="data.name" :sub-title="user.jobresponsibilities">
          <p class="card-text">
            {{data.description}}
          </p>
          <b-btn v-b-toggle="'collapse'+index" @click="showCollapse(data)">Toggle Collapse</b-btn>
          <b-collapse :id="'collapse'+index">
            <b-card>
              description
            </b-card>
          </b-collapse>
        </b-card>
      </div>

    </div>
  </b-container>
</div>
</template>

<script>
import Header from '@/components/Header'
export default {
  name: 'dashboard',
  components: {
    Header
  },
  mounted() {},
  methods: {
    showCollapse(data) {
      this.colSize = 'col-8'
    }
  },
  data() {
    return {
      user: this.$store.getters.getUser,
      projects: this.$store.getters.getProject,
      colSize: 'col-4',
      show: false
    }
  }
}
</script>

<style lang="scss">
#projects {
    background-color: rgb(243, 243, 243);
}
</style>

Link to Store.js: https://jsbin.com/kejinihoci/edit?js

https://i.sstatic.net/wXewe.png

My goal is to change the column size and show the collapsible section only for the specific item when the toggle button is clicked.

I attempted to add an ID to the v-model to use it in my method, but without success.

Answer ā„–1

For a more dynamic approach, consider assigning a unique ID (id="'collapse'+index") to each collapse element and using the v-b-toggle directive within the corresponding button v-b-toggle="'collapse'+index":

   <b-btn v-b-toggle="'collapse'+index" class="m-1">Toggle Collapse</b-btn>
      <b-collapse id="'collapse'+index" >
        <b-card>
          description
        </b-card>
      </b-collapse>

To dynamically change the class, add a property named descShown to your projects array.

In the getProject action within your store:

        let project = resp.data.project
        project=project.map((p)=>{
               p.descShown=false;
               return p;
               })
        commit('getProject_success', {
          project
        })

Within the template:

    <div :class="['col-8':data.descShown,'col-6':!data.descShown}" v-for="(data, index) in projects" :key="data._id">

   ...
  <b-btn v-b-toggle="'collapse'+index" @click="showCollapse(index)">

Your method should look like this:

   showCollapse(index) {
        this.$set(this.projects,index,true);
     }

Answer ā„–2

Take advantage of Vue's component-based architecture by creating a new component for your <b-card>. Pass the necessary props down to the component to ensure each one has its own data and methods.

  <div :class="colSize" v-for="(data, index) in projects" :key="data._id">
    <b-card 
        :cardinfo="{
           data.name,
           user.jobresponsibilities
        }"
    ></b-card>
  </div>

Vue.component('b-card', {
  props: {
    cardinfo: {
        type: Object
    }
  }
}

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

When it comes to React, an unspoken truth is that undefined could potentially cause issues

I have been attempting to iterate through an array of data, following a guide without much success. The structure of the data file is as follows: import React, {Component} from 'react'; export default [ { id: 1, lk:593458, ld:18033, status: &ap ...

What is the best way to connect a data property to dynamic elements?

Once the page loads, an SVG file's content will be injected into the page. Is there a method to connect a data property to an element within the SVG in order to achieve something like this: <g :data-type="type">...</g> or perhaps this: ...

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

Embark on the journey of incorporating the Express Router

My Nodejs server is set up with router files that use absolute routes for the HTTP methods, such as /api/users/all. // /routes/user.routes.js module.exports = (app) => { app.use((req, res, next) => { res.header( "Access-Control-All ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

Is it possible to overlay a three.js scene onto an HTML video element?

A project I am working on involves developing an AR app that can display markers for North, East, South, and West using a smartphone camera. The goal is to create a scene with a transparent background that can be overlayed on a video feed from the camera. ...

Removing a child element in ReactJS that was dynamically created based on a count

Currently, I'm working on a project with two React components: TrackSection (the parent element) and TrackItem (the child). The TrackSection contains a button that adds a new TrackItem every time it is clicked by incrementing the numTracks variable. W ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

Generating random numbers from an array can be done while excluding certain specified numbers

I'm currently developing a game where players are required to choose 6 numbers between 1 and 36. My goal is to create a new array that does not include the 6 selected numbers, resulting in an array that is 30 numbers long. Here is my approach: The ...

Mongodb failing to recognize the concat function

I have a field within my collection that looks like this: uniqueId: 123 inTarefa: true exclude: "ab,cd," orderId: 987 I am attempting to update all of the values using a "FindOneAndUpdate" query like so: collection.findOneAndUpdate({ 'uniqu ...

Ensuring the correctness of past and upcoming dates with vee-validate in vue.js

I am currently utilizing vee-validate for the purpose of validation. <datetime v-validate="'required'" format="YYYY-MM-DD H:i:s" name="futureDates" width="100px" :class="['form-control', { ...

Looking to adjust the width of a <div> element dynamically as the browser window resizes using jQuery

I am facing an issue where the width of a <div> should change based on the browser size using jQuery. Below is the code I have written for this functionality. if ($(window).width() > 990 && $(window).width() < 1190) { $("#greybor") ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

A Vue.js component containing a decimal variable within its data

When working with data in a Vue.js component, the decimal type is not included among the possible types (String, Number, Boolean, Array, Object, Date, Function, Symbol). How can we define a variable of this type? ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

Working with numerous query parameters within AngularJS

When interfacing with an external service, Iā€™m receiving query parameters in the following format: url/?error=someError&error_description=someErrorDescription In my app.js file, I have attempted to handle this using the routeProvider as shown below ...

Utilize Vue's prop system to pass objects between components

Can you help with passing objects as props in Vue? It seems like a simple task, but I'm having some trouble. In my .vue file, I have the following code: <template> <div id="scatter"></div> </template> <script&g ...

Is it necessary to use `top` or `parent` when utilizing local scripts in an iFrame?

Is it possible to eliminate the use of top or parent in iFrame localized scripts, as the title suggests? Upon examining the screenshot below, I encounter a "not defined" error unless I include top or parent as a prefix to my function call. test(); does n ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...