Steps for changing the selected class using a universal click event

As I make my component library in Vue, one specific element I've defined is a custom checkbox. The code for this component looks like this:

<template>
    <div class="checkboxcont" :class="{'checkboxcont-selected': isSelected}" @click="clickevent">
        <span class="j-checkbox">
            <input type="checkbox" />
        </span>
        <slot></slot>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                isSelected: false
            }
        },
        methods: {
            clickevent(event) {
                if(this.isSelected) {
                    this.isSelected = false;
                } else {
                    this.isSelected = true;
                }
            }
        },
    }
</script>

My objective now is to ensure that when I click on the checkbox, it sets the 'isSelected' data property to false and assigns the CSS class 'checkboxcont-selected-last' to the component. Additionally, I want this added class to be removed once I click on another checkbox component. How can I achieve this functionality through event listening? I attempted using vanilla JavaScript to manipulate DOM classes but encountered issues integrating it with Vue.js bindings:

clickevent(event) {
    if(this.isSelected) {
        this.isSelected = false;
        this.$el.classList.add("checkboxcont-selected-last");
    } else {
        this.isSelected = true;
    }
}

I'm unsure how to address this problem effectively. Can you offer any guidance?

For styling, I utilized Less as follows:

<style lang="less" scoped rel="stylesheet/less">
    @import '../../mixin/mixin.less';
    /* Styling rules */
</style>
<style lang="less" rel="stylesheet/less">
    @import '../../mixin/mixin.less';
    /* Additional styling rules */
</style>

After trying various approaches involving `this.$el` and native DOM operations, I found limitations while manipulating other components based on their classnames in conjunction with Vue bindings. Is there an alternate method or approach that you'd recommend?

Answer №1

If you're looking for a more efficient way to dynamically add or remove classes, consider using v-bind:class in Vue.js. There are various approaches you can take to apply a dynamic class based on a Vue data variable.

It seems like you're already utilizing it:

<div class="checkboxcont" :class="{'checkboxcont-selected': isSelected}" @click="clickevent">

In this case, the div will have the class checkboxcont only if isSelected is false, and both classes checkboxcont and checkboxcont-selected if isSelected is true.

Revised:

If you need to add a class to the DOM from another component, there are two methods I can suggest:

  1. Using Web API: If you know the element's id where you want to add a class, you can use Element.className like this:

var d = document.getElementById("yourElem"); d.className += " otherclass";

  1. Vuex approach: You can utilize a centralized state managed by Vue or implement Vuex for state management. These state variables can be modified across components and used for dynamic class addition/removal.

For further insights into Vuex, you can refer to my response on this thread.

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 it achievable to dynamically append items to an array and have Vue.js automatically recognize them?

update 2 I am facing an issue related to referencing an array from a parent component. You can find a fiddle in the comments section below. In my app, we need to be able to dynamically add items to a menu header. I have tried pushing items to the end of ...

Dealing with ASP.NET forms that involve a javascript plugin generating substitute input

I'm facing an issue with my ASP.NET MVC webpage where I submit a form using AJAX in the following way: function ValidateFormAndAjaxSubmit(formId, callingElement) { if (IsNotDblClick(callingElement.id)) { var _form = $("#" + formId); ...

Encountering an "UNDEFINED" result after executing a basic for loop in a beginner's JavaScript program

function reverseArrayItems(arr) { for (let i = arr.length - 1; i >= 0; i--) { console.log(`${arr[i]}`); } }; const words = ['reversed', 'be', 'should', 'order', 'The']; console.log(reverseArray ...

Exploring Vuex, monitoring changes with watchers, and delving into lifecycle hooks with Server-Side Rendering in

I understand that a watch runs before the beforeUpdate lifecycle event occurs. However, I have certain tasks in the watch block that are crucial to complete before the virtual DOM is re-rendered or updated. This is how my watch block looks like: setup () ...

What causes offsetHeight to be less than clientHeight?

INFORMATION: clientHeight: Retrieves the height of an element, taking into account padding offsetHeight: Obtains the height of an element, considering padding, border, and scrollbar Analyzing the Data: The value returned by offsetHeight is expected to ...

Encountering issues with parsing normals in THREE.js json mesh format

UPDATE: The demo is finally live! Check it out here: . Use the dropdown menu to switch between torus models and see the issue in action. Please note that WebGL MRT extensions are required for this demo. I have been working on developing my own WebGL defer ...

Type in the Datepicker field to input text

Utilizing jQueryUI, I successfully integrated a datepicker into a textfield. However, this implementation now restricts the ability to manually input any text into the field. Users can only select a date from the datepicker. I would like to allow users to ...

Display the object that matches all strings in an array in JavaScript

I need help displaying matching countries based on the codes provided in the returned array below. Returned Array: ["USA", "FRA", "GBR"] List of Countries: export const COUNTRY_CODES = [ { country: "United States ...

Iterate over the div elements that have a class of X to discover any potential connections with the div elements

I've been working on a script that aims to accomplish the following: Iterate through each .display-player-box element and assign its id to a variable. Loop through the .removefromsquad elements to find one whose class attribute corresponds with the ...

Utilizing JSON Filtering in JavaScript/TypeScript

My JSON data structure is as follows. const obj = { data:{name:"name1", type:"abc"}, parent:{ data: {name:"parent1"}, parent:{ data: { name:"superparent1"}, parent: null } } } I am looking to extract the final output as "super ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

updating a d3js line graph in real-time using JSON information

Trying to wrap my head around dynamically updating a line graph with new data, shifting the graph to the left and adding fresh data from the right - you following me? Want it to behave just like the examples on I'm fairly new to d3 (javascript) and l ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

Storing a value from an external JavaScript variable into an HTML variable involves a few key steps

Is there a way to transfer the jQuery variable value to an HTML variable? Take a look at my code, This is the JavaScript function that resides in an external script function createImage(settings) { var kk = createCanvas(settings)[0].toDataURL(' ...

How can one access the property "this.var" within a function declared within an object

I stumbled upon this snippet of code var person = { name: "joseph", age: 33, favSong: function killingInTheTameOf(){ this.lyrics = "Those who died are justified"; } }; document.write(person.lyrics); //doesn't work My curiosi ...

The output is consistently null

I'm encountering an issue with my implementation of the GCD function using recursion. Whenever I try to return a value, it always comes back as undefined. However, when I use console.log(value), it displays correctly on the screen. Below is the code ...

The extent of an array populated within a jQuery getJson method

I'm facing an issue where I need to populate an array using multiple jQuery get JSON functions and then access the array once all data has been inserted. The problem I encountered is that the data seems to be scoped only within each individual functi ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Refreshing the empty array in Vue with Vue-Paginate does not work

I have integrated vue-paginate into my application and I've encountered a situation where refreshing an empty array with new contents does not display the data. <paginate name="recipes" :list="recipes" :per="16" class="p-0" > <tr ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...