I am trying to create a list of projects, and I want the user to select one of them to be the default project (to use it later with other processes).
My problem is, I have a list of projects and each one has a unique id and set the default class is RegularIcon
, as follows:
<span :id="project.id" class="RegularIcon" @click="changeIcon(project.id, projectKey)"></span>
projectKey
is the index of the current project in the list.
My function as following:
changeIcon: function(projectId, projectIndex) {
let ClassName = document.getElementById(projectId).className;
if ( ClassName == 'RegularIcon' )
{
var x = document.getElementsByClassName("SolidIcon");
var i;
if ( x.length != 0 )
{
for ( i=0; i < this.ProjectsList.length; i++ )
{
if ( i != projectIndex )
{
x[i].className = 'RegularIcon';
}
else {
x[i].className = 'SolidIcon';
}
}
}
else
{
document.getElementById(projectId).className = 'SolidIcon';
}
}
else
{
document.getElementById(projectId).className = 'RegularIcon';
}
},
My idea was when the user clicks on the icon (default it not filled) then after clicking on it will be solid and filled and at the same time, all other projects icons will be (not filled - regular).
But I'm got an error message :
Uncaught TypeError: Cannot set property 'classList' of undefined
Instead of DOM manipulation, you could use Vue's class binding to set a specific class based on a condition:
<span :class="{ CLASS1: CONDITION1, CLASS2: CONDITION2, ... }">
In your case, the binding would be:
<span :class="{ RegularIcon: CONDITION, SolidIcon: !CONDITION }">
...where CONDITION
is based on user selection (eg, the index of the selection). For instance, RegularIcon
could be active when the icon's index does not match the selected index; and SolidIcon
could be active when the index matches.
<div v-for="(project, i) in projects">
<span :class="{ RegularIcon: i !== selectedIndex, SolidIcon: i === selectedIndex }"
@click="selectedIndex = i"></span>
</div>
new Vue({ el: '#app', data: () => ({ selectedIndex: -1, projects: [ {id: 1}, {id: 2}, {id: 3}, ] }), })
<script src="https://unpkg.com/vue@2.5.17"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" integrity="sha384-/rXc/GQVaYpyDdyxK+ecHPVYJSN9bmVFBvjA/9eOB+pb3F2w2N6fc5qB9Ew5yIns" crossorigin="anonymous"> <div id="app"> <div v-for="(project, i) in projects" :key="project.id"> <span class="fa-ghost" :class="{far: i !== selectedIndex, fas: i === selectedIndex}" @click="selectedIndex = i"></span> </div> </div>
Try using
document.getElementById(projectId).classList.add("classToAdd");
document.getElementById(projectId).classList.remove("classToRemove");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.