Disabling a property within a v-for loop depending on the component's prop

Consider this scenario:

<v-btn v-for="action in actions" :key="action.icon" :disabled="action.disabled" icon
       @click="action.click(item.id)">
  <v-icon>{{ action.icon }}</v-icon>
</v-btn>

The 'actions' object is defined as follows:

export default {
  props: {
    rowEditingDisabled: Boolean,
  },
  data() {
    return {
      actions: [
        {icon: 'mdi-pencil', disabled: this.rowEditingDisabled, click: this.edit},
      ],
    };
  },
};

How can I ensure the 'disabled' property updates when the 'rowEditingDisabled' prop of the component is updated?

This code snippet illustrates the issue:

Vue.component('child', {
  template: `
    <div>
      <v-btn :disabled="rowEditingDisabled">This works!</v-btn>
      <v-btn v-for="action in actions" :key="action.icon" :disabled="action.disabled" icon
         @click="action.click(item.id)">
        <v-icon>{{ action.icon }}</v-icon>
      </v-btn>
    </div>`,
  props: {
    rowEditingDisabled: Boolean,
  },
  data() {
    return {
      actions: [
        {icon: 'mdi-pencil', disabled: this.rowEditingDisabled, click: this.edit},
      ],
    };
  },
})
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      isDisabled: true
    };
  },
  created() {
    setInterval(() => {
      this.isDisabled = !this.isDisabled;
    }, 1000);
  },
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2848d8c96a2d4cc9a">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cfccdccdd0dfc0f98b97c1">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <child :row-editing-disabled="isDisabled"></child>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbdbeae8bf9e5b3">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a4a7b7a6bbb4ab92e0fcaa">[email protected]</a>/dist/vuetify.js"></script>

While the use of the prop works fine, the same behavior seems to break when included within an array.

Answer №1

Make sure you keep an eye on the prop changes like so:

export default {
    props: { isRowEditingDisabled: Boolean, },
    data() {
        return {
            buttons: [{
                icon: 'mdi-pencil',
                disabled: false, 
                onClick: this.edit
            }], 
        }; 
    },
    watch: { 
        isRowEditingDisabled: function(updatedValue, previousValue) { 
            // monitor it closely
            console.log('Updated Prop Value: ', updatedValue, ' | Previous Value: ', previousValue);
            this.buttons[0].disabled = updatedValue;
        }
    },
};

Answer №2

Utilize the data() function to access the properties of the component by using this.

Give this a shot :

data () {
    return {
      actions: [
        {icon: 'mdi-pencil', disabled: this.rowEditingDisabled, click: this.edit},
      ],
    };
  }

Update : I have put together a functioning code snippet based on the previous explanation and everything seems to be in order. Please double-check the naming convention of the props in the template, it should use hyphens as separators. For example, :row-editing-disabled="...".

Live Demo :

Vue.component('post', {
  template: '#post-template',
  props: {
    rowEditingDisabled: Boolean
  },
  data() {
    return {
      actions: [
        {icon: 'mdi-pencil', disabled: this.rowEditingDisabled, click: this.edit}
      ]
    };
  }
});

var vm = new Vue({
  el: '#app',
  data: {
    isRowEditingDisabled: true,
  }
});
<script src="https://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>
<div id="app">
  <post :row-editing-disabled="isRowEditingDisabled"></post>
</div>

<template id="post-template">
  <button v-for="action in actions" :key="action.icon" :disabled="action.disabled">
    Click Me!
  </button>
</template>

Answer №3

Sometimes there may be a delay in receiving props. In such scenarios, to maintain dynamic behavior, you can utilize computed properties. Please review the updated lines below

Vue.component('child', {
  template: `
    <div>
      <v-btn v-for="action in actions" :key="action.icon" :disabled="disableRow" @click="action.click(item.id)"> <!-- ***Changes made here*** -->
        <v-icon>{{ action.icon }}</v-icon>
      </v-btn>
    </div>`,
  props: {
    rowEditingDisabled: Boolean,
  },
  data() {
    return {
      actions: [
        {icon: 'mdi-pencil', click: this.edit},// ***Updated changes***
      ],
    };
  },
 // ***Modified section below***
 computed: {
   disableRow() {
    return this.rowEditingDisabled;
   }
 }
})
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      isDisabled: true
    };
  },
  created() {
    // ***Updates made here***
    // Commenting out the following as it toggles the flag to false
    /* setInterval(() => {
      this.isDisabled = !this.isDisabled;
    }, 1000); */
  },
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89e97968cb8ced680">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="304645554459564970021e48">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <child :row-editing-disabled="isDisabled"></child>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4828191b4c6da8c">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a7b6aba4bb82f0ecba">[email protected]</a>/dist/vuetify.js"></script>

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

Is there a way to toggle between an Arabic and English CSS file within a Vue3 js project?

I used vue-cli to create my project and imported css files in my main.js file. Now, I am looking for a way to load different css files depending on whether the user chooses to view the website in RTL or LTR languages. If the user selects RTL, I want to l ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request Original query: I am utilizing the file_picker_callback type image I have enabled the image_description input field in my ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

Tips for organizing JSON information in ReactJS

Could someone lend a hand with sorting JSON data in ReactJs? I'm having trouble getting it to work properly. Also, if I want to sort by title, would it be the same process? Thanks! This is what I've tried so far: componentDidMount() { ...

The regular expression is not matching the expected pattern

Here is an interesting scenario involving a Javascript regular expression matching operation: "class1 MsoClass2\tmsoclass3\t MSOclass4 msoc5".match(/(^|\s)mso.*?(\s|$)/ig); When running this operation, the expected result would be [" ...

Creating a Comprehensive Page Design with Bootstrap and the Latest Version of Vue

My goal is to develop a Single Page Application using Vue3 and the Bootstrap 5 framework with a simple layout of Header -> Content -> Footer. I want the Content section to fill the space between the header and footer, ensuring there is no overlap. Ho ...

Utilizing data retrieval caching in nextjs getServerSideProps() for optimized performance

I am currently developing an application using nextjs that retrieves data from a firebase firestore. The issue I am facing is that the application makes these requests on every page load, even when the data does not need to be completely up to date. To add ...

Tips for accessing the parent of an LI element

Hey there, I've set up a drop-down menu using LI and UL tags. For example: <ul> <li><a href="#">Parent 1</a> <ul> <li id = "Child 1"><a href="#">Child 1</a></li> ...

Trouble with displaying image sources in dynamic content with Vue and Vuetify

Currently, I am developing a component that displays tabs along with their corresponding HTML content using v-tab, v-tab-items, and v-tab-item. In the v-tab-item section, I have included the following snippet: <v-card flat> <v-card-text v-html=& ...

Using v-for to pass two properties to a single component in VueJS

Hey there! I'm trying to create a v-for loop with a component that has two different props COMPONENT <template> <div class="bg-light rounded p-2 px-5"> <h5> {{ number }}</h5> <h3>{{ item }} ...

The error message "AWS Lambda Node 18: fetch is not defined, please resolve or include global fetch" indicates that

Seeking assistance with calling the Pagespeed Insights API from an AWS Lambda using Node 18. Struggling to make fetch() function properly. Cloudwatch logs indicate the message "inside the try about to fetch," but then nothing else appears. The Lambda con ...

`Creating a fluid MySQL table using JavaScript`

One of the challenges I'm facing involves working with a MySQL table that consists of 3 columns: MySQL db table +--+----+-------------+ |id|data|display_order| +--+----+-------------+ |0 |0 |2 | +--+----+-------------+ |1 |1 |1 ...

Vuetify Slide Groups when clicked on, will toggle on and off

Referencing the most recent example found on this page: https://vuetifyjs.com/en/components/slide-groups I am currently attempting to comprehend the mechanics behind the following code snippet: <v-slide-item v-for="n in 15" :key="n" v-slot:de ...

Hide the button with jQuery Ajax if the variable is deemed acceptable upon submission

I need to figure out how to hide the submit button if the email entered is the same as the one in the database from action.php. Can anyone help me with integrating this functionality into my existing code? <form onsubmit="return submitdata();"> ...

The $size property in mongoose is always returning zero for me

Hello, I've encountered an issue where the $size property in my aggregate query always returns 0 after adding $addFields. Below are the details of my tables and query: Table: post { _id: 1, text: 'some text', } Table: comments { _id: 1, te ...

The Angular routing feature seems to be malfunctioning

I have encountered a frustrating issue with AngularJS routing and despite countless searches for solutions, I am still facing the same problem. In my root folder at c:\intepub\wwwroot\angular\, I have three files that I am testing under ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Tips on revealing div elements using a slide-down animation exclusively with JavaScript

I am looking to display a div with a slide-up effect using JavaScript (not jQuery) when clicked. Here is the HTML code I have: <div class="title-box"><a href="#">show text</a></div> <div class="box"><span class="activity- ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...