Leveraging conditional statements for dynamically computed Vue properties

In the Vue site I'm working on, there is a functional button that changes its state when clicked (from "pause" to "resume" and also changes colors). The button functionality itself works perfectly, but I am facing an issue in aligning it with another value on the same page. There is a function that contains an object called details, which has a key named status holding values of either "H" or "P".

My goal now is to ensure that upon page load, if the status is "H", the button should display 'Resume', and if it's "P", the button should display 'Pause' (meaning, turn off isOpen for "H" and turn it on for "P"). Unfortunately, I can't include conditional statements in the data return. Is there a way to achieve this using computed properties?

<button class="btn btn-block" :style="{ color: pauseButton.textColor, backgroundColor: pauseButton.background, border: none, borderRadius: .15 }" v-on:click="pauseTask" type="button" role="button" id="" aria-expanded="false">
{{ pauseButton.text }}
</button>

data() {
    return {
        details: [],
        pauseButton: {
            text:'Pause',
            textColor: '#6c757d',
            background: '#BDE5F8'
        },
        isOpen: true,
    }
},
pauseTask: function() {
      this.isOpen = !this.isOpen;

      //This line doesn't function as intended
      if(this.details[0].status === 'H'){
        !this.isOpen;
      }

      this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume';
      this.pauseButton.background = this.isOpen ? '#BDE5F8' : '#FEEFB3';
      this.pauseButton.textColor = this.isOpen ? '#6c757d' : '#ff6e6e ';
    },

Answer №1

If you have an Array called details and need to loop through it to generate multiple elements, consider using the following method to simplify the process.

new Vue({
  el: '#app',
  data() {
    return {
      details: [{
        status: 'H'
      }, {
        status: 'H'
      }, {
        status: 'P'
      }]
    }
  },
  methods: {
    toggleTask(d) {
      d.status = (d.status == 'H' ? 'P' : 'H')
    }
  }
});
.btn {
  border: none;
  border-radius: .15;
  margin: 4px 0;
  padding: 4px 10px;
}

.btn.resume {
  color: #ff6e6e;
  background-color: #FEEFB3;
}

.btn.pause {
  color: #6c757d;
  background-color: #BDE5F8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-for="(d, i) in details" :key="i">
    Status: {{ d.status}}
    <button 
      :class="['btn', 'btn-block', d.status == 'H' ? 'resume' : 'pause']" 
      @click="toggleTask(d)" 
      role="button" 
      aria-expanded="false">
      {{ d.status == 'H' ? 'Resume' : 'Pause' }}
    </button>
  </div>
</div>

Answer №2

In the mounted or created lifecycle method, make sure to set the isOpen value to the opposite of its current state only when the status is 'H'.

mounted(){
  if(this.details[0].status === 'H'){
    this.isOpen = !this.isOpen;
  }
},
pauseTask: function() {
      this.isOpen = !this.isOpen;

      this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume';
      this.pauseButton.background = this.isOpen ? '#BDE5F8' : '#FEEFB3';
      this.pauseButton.textColor = this.isOpen ? '#6c757d' : '#ff6e6e ';
    },

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

Invoke React Component Function using onclick in dangerouslySetInnerHTML

I'm new to React and I have a contenteditable div with dangerouslySetInnerHTML as the child, for formatting user input at runtime. When a specific span is clicked inside the HTML, I want to update a variable in the parent component using setState. Is ...

Is it possible to extract external JSON data using JQuery's $.getJSON function?

I am trying to retrieve a quote from the iheartquotes website and display it within a div when my webpage loads. However, for some reason, the code I have written is not working as expected. <script type="text/javascript"> $(document).ready( ...

A comprehensive guide on publishing an application to Heroku using MongoDb/Mlab

I am encountering difficulties in deploying my Node.JS application to Heroku. I suspect that the issue lies with the database, but I cannot pinpoint the exact problem. I have attempted to switch from MongoDB Atlas to Mlab in hopes of resolving the issue, h ...

The React lifecycle method componentDidMount is failing to execute

In my React application, I have the following route setup: <Route path={`${this.props.match.path}horoskop`} render={() => <HoroscopeController horoscopeService={this.horoscopeService} fortuneTellerService={this.fortuneTell ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

Issue with Ionic displaying data from AngularJS $http.get request

Having just started learning AngularJS, I have followed tutorials on YouTube and read the documentation, but I am struggling to display data from an API using the $http.get() request. Here is my JavaScript and HTML code: var exampleApp= angular.modul ...

What is the best way to retrieve a value from a promise in JavaScript?

As someone who is relatively new to working with promises, I find myself in a bit of a sticky situation. Despite reading several articles and Stack Overflow posts on the topic, I still can't seem to fully grasp it. My dilemma involves a simple API th ...

The primary directory specified in the package.json file

Question: I have a pre-existing library that I want to turn into an NPM module. Currently, the library is being required through the local file system. How can I specify the main directory path for my module's files? If my structure looks like this: ...

What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScr ...

Why is there an issue with the JavaScript array when accessing data['sax']?

There seems to be some confusion regarding the contents of this array and how it assigns values to the variable set. It would be greatly appreciated if someone could provide an example pertaining to the usage of data['sax']. Additionally, an expl ...

transform data into JSON format and transmit using jquery ajax

I have one object: var myobject = {first: 1, second: {test: 90}, third: [10, 20]}; and I need to convert it into a JSON string using jQuery ajax. Can someone please advise on how to achieve this? (I tried using JSON.stringify(), but it didn't work ...

What is the best way to establish a connection between two applications using React and Node

Currently, I am facing a challenge with integrating two separate applications. One is a login/registration form written in Node.js, Express.js, React.js, and MySQL. The file structure looks like this: https://i.sstatic.net/th6Ej.png The other application ...

Problem with geocoding to retrieve a list of terrestrial coordinates

I am currently working on developing a functionality that can return an array of land-based coordinates. I have utilized Google's geocoder to create individual land-based coordinates successfully, but now I want to implement it in a way where an array ...

Vue Router seems to be causing redundant entries in window.history when using Safari browser

Within my App.vue, the setup is as follows: // App.vue <template> <div id="app"> <router-view/> </div> </template> In addition, the Home.vue contains a link to Gmap.vue: // Home.vue <template> <div> ...

Prevent using href for opening the browser when clicked

In the control, there is an href link that triggers a javascript function and passes a variable to it: <a href="<%#XPath("link").ToString()%>" onclick="return getLink(this)">Link</a> I'm looking for a way to prevent the browser fro ...

What is the reason behind Babel including this redundant line of code in my build?

While utilizing Babel 7 and Gulp 4 in conjunction, I have noticed that the subsequent line of code is repeated five times within my build: function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterato ...

Is node.js required for utilizing Angularjs?

Considering incorporating angular.js into my website's Image Editing Tool. Is node.js necessary for this integration? I'm a bit puzzled here. Are there instances where both nodejs and angularjs are used together, or can they operate independentl ...

Attach a tab-icon to a picture

I am looking to add a tab to the bottom border of an image within a gallery. This tab needs to be right up against the image border with no space in between. When clicked, this tab should activate a small JavaScript function that will display the content ...

Changing a 64-bit Steam ID to a 32-bit account ID

Is there a way to convert a 64-bit Steam ID to a 32-bit account ID in Node.js? According to Steam, you should take the first 32 bits of the number, but how exactly can this be done in Node? Would using BigNumber be necessary to handle the 64-bit integer? ...

Validation of Email Existence (Using Django and Javascript/Ajax)

I'm currently facing a challenge with building an E-mail validator using Django and Javascript/Ajax. Despite my efforts, I seem to be stuck at a certain point where the Ajax response consistently shows: {response: "This field is required.", email: fa ...