I have a problem how to add style to ul inside clicked li with Vue JavaScript. My html code:
<ul>
<li>Menu</li>
<li @click="toggleSubMenu">Profile
<ul> //Add class here
<li>History</li>
</ul>
</li>
<li @click="toggleSubMenu">Media
<ul :>
<li>Photos</li>
<li>Videos</li>
</ul>
</li>
</ul>
And my vue code:
<script>
import { reactive } from 'vue'
export default {
setup(){
const data = reactive({
sub_menu_show: '',
});
const toggleSubMenu = () => {
data.sub_menu_show = !data.sub_menu_show
}
return{
data,
toggleSubMenu
}
}
}
</script>
But, and my expectation is when toggleSubMenu clicked, the ul style added is only inside li that clicked, not add to all ul or other sub menu.
Thanks before.
CodePudding user response:
Currently, you are using a single state for multiple UI elements. How about this instead:
<ul>
<li>Menu</li>
<li @click="() => toggleSubMenu('profile')">Profile
<ul :>
<li>History</li>
</ul>
</li>
<li @click="() => toggleSubMenu('media')">Media
<ul :>
<li>Photos</li>
<li>Videos</li>
</ul>
</li>
</ul>
<script>
import { ref } from 'vue'
export default {
setup(){
const toggleStates = ref({ profile: false, media: false });
const toggleSubMenu = (type) => {
toggleStates.value[type] = !toggleStates.value[type];
}
return {
toggleSubMenu,
toggleStates
}
}
}
</script>
CodePudding user response:
@click is a shorthand for writing v-on directive. This Vue directive by default passes an event argument that contains a lot of things including the target element to the specified callback function.
Therefore, apply the operation to that target element.
event.target.style.cssText = ''