Updating button appearance when clicked using Vue.js and Tailwind CSS

As part of my learning journey, I have expanded this code to enhance my frontend skills. While I am aware that the code can be significantly shortened, I am focused on learning and broadening my experience in frontend development.

The code below functions appropriately with local storage set to true or false, enabling the correct v-if/else section. My next objective is to adjust the local storage based on a button click event.

Can you suggest the most effective approach to achieve this?

   <div v-if="privateChat == 'false'">
          <button type="button">
                        <a key="privateChat" href="#" class="bg-red-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
                            <ChatIcon class="h-6 w-6 text-white"/>
                            <span class="pt-2">Private Chat OFF</span>
                        </a>
                    </button>
          </div>
          <div v-else>
          <button type="button">
                        <a key="privateChat" href="#" class="bg-green-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
                            <ChatIcon class="h-6 w-6 text-white"/>
                            <span class="pt-2">Private Chat ON</span>
                        </a>
                    </button>
          </div>

<script>
export default {
  data() {
    return {
      privateChat: (localStorage.getItem("privateChat") === 'true') ? 'true' : 'false',
     }
   },
  methods: {
    clickPrivateChat (value) {
      this.privateChat = value === true ? "true" : "false";
      localStorage.setItem("privateChat", value);
    },
  setup() {
    const enabled = ref(privateChat)
    let value = localStorage.getItem("privateChat");
    let privateChat = (value === 'true');
    }
</script>

Answer №1

If you want to enhance the functionality, consider these suggestions...

  • Opt for actual true/false values rather than using strings like "true" or "false"
  • Practice DRY programming: Utilize a single button and employ a Vue computed value to display either "ON" or "OFF"
  • Employ conditional logic with :class to implement the bg-green-900 class effectively

script:

  data() {
        return {
            privateChat: (localStorage.getItem("privateChat") === true) ? true : false,
        }
    },
    computed: {
        onOrOff() {
            return this.privateChat  ? 'ON' : 'OFF'
        }
    },
    methods: {
        clickPrivateChat (value) {
          this.privateChat = !this.privateChat
          localStorage.setItem("privateChat", value)
        },
        setup() {
            const enabled = ref(privateChat)
            let value = localStorage.getItem("privateChat")
            let privateChat = (value === true)
        }
  },

markup:

 <div>
    <button type="button" @click="clickPrivateChat">
        <a key="privateChat" href="#" :class="privateChat?'bg-green-900':''" class="bg-red-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
            <span class="pt-2">Private Chat {{ onOrOff }}</span>
        </a>
    </button>
 </div> 

enhanced Vue approach

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

What is the best way to efficiently loop through elements and add them to a new array in JavaScript while optimizing performance?

Here's the code in question: let newArr = [] const items = [ { name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', &apos ...

Anticipated semicolon in the JavaScript file

I recently came across the dialogflow demo as a reference. However, I encountered an error stating 'semicolon expected' at the method sendTextMessageToDialogFlow. How can I resolve this issue? Below is the code snippet: router.post('/dialo ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...

Tips for adjusting the color of the white tick in Material UI Checkbox with React and JavaScript

I'm currently attempting to customize the default white tick (not the checkbox background!) and change it to a different color that I choose. While I have come across solutions for earlier versions of MUI and React, I am specifically looking for a sol ...

Is there a way to locate a null string within this data arrangement?

I am looking to create functionality where, when a button is clicked, the application checks the state and takes different actions based on the result. Specifically, I want to ensure that there are no empty "value" fields, and if there are, redirect to ano ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

Issue encountered during ag-grid version upgrade: unable to locate compatible row model for rowModelType 'virtual'

Recently, I updated my ag-grid version from v7.0.2 to v11.0.0, and after the upgrade, all tables with infinite scrolling functionality stopped working abruptly. The browser console displayed the following error message: ag-Grid: count not find matching ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

Adding and removing dynamic fields with Bootstrap functionality

Recently, I've been trying to develop a feature where users can add and remove fields by clicking on a button. However, I've encountered a roadblock in my progress. If you take a look at this CodePen link, you'll see what I have so far. My a ...

Is it possible to include all visible content, even when scrolling, within the full page height?

My webpage contains content that exceeds the height of the window. I am looking for a way to retrieve the full height of my page using either jQuery or pure Javascript. Can anyone provide a solution? I have considered the following approach: $('body ...

Is the original object cloned or passed by reference when passing it to a child React component through props?

When passing an object to a child component through the components props in React, does the object get cloned or does it simply pass a reference to the original object? For instance, in my App.js, I am importing a JSON object called ENTRY_DATA. Then, I pa ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

"Error encountered when making a request to Google API using Ember.js, response remains

Trying to fetch place suggestions from Google API using Ember js. Below is the code snippet for the service module: fetch(){ let url=`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY` return Ember.RSV ...

Exploring connections among Array Objects on a Map

Here are some JSON examples of Pokemon Battles: [ { "battleID": "1", "trainers": [ { "LastName": "Ketchum", "ForeName": "Ash" }, { "LastName": "Mason", ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

What is the maximum depth allowed in Vue?

My Vue component has the following structure: <transition name="fade"> <div> <div v-if="false"> </div> <div v-else=""> <div> <div> <div>no matter what content</div> ...

Encountering an issue with DateTimeField being undefined in a React.js application

I encountered an issue stating that DateTimeField is not defined while attempting to create a date picker in react + bootstrap. I referred to the following URLs for assistance: https://github.com/Eonasdan/bootstrap-datetimepicker Link to my code s ...

Issues with AngularJS Directives not functioning properly when elements are added dynamically through an AJAX request

I am facing a scenario where I have a page featuring a modal window that is created using the AngularUI Bootstrap modal directive. The DOM structure for this modal is being dynamically loaded from the server, and it is triggered to open when a specific but ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...