VueJS when to use id and class

Viewed 1592

another question I had with regards to how Vue works, pardon if it's a silly question. I started from VanillaJS where an element is usually declared as such

<div id="testId" class="testClass">This is some test element</div>

where I then apply the necessary styling and javascript as follows

.testClass {
    border: solid red 1px;
}
document.getElementById("testId").onclick = function (){
    console.log("clicked");
}

However, after hopping over to VueJS, I can simply (in a good way) replace the above as follows

<template>
    <div class="testClass" @click="handleClick">This is some test element</div>
</template>

<script>
export default{
    methods: {
        handleClick(){ 
            console.log("clicked");
        }
    }
}
</script>

<style scoped>
.testClass{
    border: solid red 1px;
}
</style>

I noticed that I can replicate the entire example without the use of id.

I realized I haven't been using id much, is that bad? and is there any use case that I am missing out?

3 Answers

No, I don't think that is bad. Having more id's doesn't improve site experience.

The id will be the unique part of the element. In Vue, you can bind events directly, apply css using classes. So i don't see a usecase for ids. And also it is not mandatory to use ids in the elements. It is just another way addressing the element.

classes are useful to categorize a set of elements that share some properties, then you can use javascript or css to change the set of elements.

An id is used to identify a component in your page, it must be unique. It is useful if you have a page with 4 sections, so each section has its own id (section1, section2, section3, section4), then you can create a link inside the page to access to each section by using an a tag like this <a href="#section4">Go to Section 4</a>.

I found the id attribute useful to find elements in the DOM, for example, for testing purposes.

Well, that's my opinion and what I know about it :D

Related