VueJs set active class, when one li element clicked in v-for loop
Add a data
property called activeIndex
:
data() {
return {
activeIndex: undefined
}
},
and your setActive
method:
methods: {
setActive(subscription, index) {
this.activeIndex = index;
this.userSubscription.subscription_key = subscription.subscription_key
},
getSubscriptions() {
.....
// fetch subscriptions in this.subscriptions var
.....
// select preselected subscription, when fetching subscriptions
let userSubscriptionKey = this.userSubscription.subscription_key;
let indexOfObject = this.subscriptions.findIndex(
o => o.subscription_key === userSubscriptionKey
);
this.setActive(this.userSubscription, indexOfObject);
}
}
with a slight modification to your template:
<ul>
<li v-for="(s, index) in subscriptions"
:class="{ 'active': activeIndex === index }" :key="s.id"
@click="setActive(s, index)">
{{ s.name }}
</li>
</ul>
You basically set an index that should be active and that's it. active
css class is added when list element's index is the same as activeIndex
.
As for setting activeIndex
to existing choice before the user changes it, you can set activeIndex
when fetching subscriptions data to user's current subscription.
Fiddle: http://jsfiddle.net/eywraw8t/256701/
VueJs set active class to the data coming from API, when one li element is clicked in V-for loop
Add property called activeId
to your data object and update it in the selectCountry
method:
data() {
return {
defaultCountry: "CST",
Options: [],
activeId:-1
}
},
methods:{
selectCountry(item){
...
this.activeId=item.id;
}
}
in the template add the class binding :
<li class="country-menu-item" :class="{'active':item.id===activeId}" v-for="item in Options"
VueJs set active class, when One li element is clicked in dropdown using V-for loop
First your data option should be a function that returns an object, second use a computed property based on help
property to add class
field :
data(){
return{
openTypeView: false,
active_id: 1,
help: [
{
name: "Users",
id: 1,
liId: 'g1',
class: 'active',
},
{
name: "Profile",
id: 2,
liId: 'g2',
class: '',
},
],
}
},
computed:{
customHelp(){
return this.help.map(item=>{
item.class= this.active_id===item.id?'active':''
return item;
})
}
}
then loop through that computed property :
<li class="type-li-item" v-for="item in customHelp" :id="item.liId"
:key="item.id" :class="item.class" @click="active_id=item.id">
<span>{{ item.name }}</span>
</li>
How to set active class in vue 3 on active item when clicked
I used selectedItem.value in setup.
This is because in the setup function, selectedItem has a type of Ref, where in the template the internal value is directly available that's why we use there as selectedItem simply.
Also i modified :class code a bit which makes it work.
<template>
<ul class="items">
<li
class="item"
v-for="(item, index) in items"
:key="index"
@click="selectItem(index)"
:class="{ active: index == selectedItem }"
>
{{ item }}
</li>
</ul>
</template>
<script lang="ts">
import { defineComponent,ref } from "vue"
export default defineComponent({
name: "Test",
props: {
id: Number,
item: Object,
},
setup(props) {
const selectedItem = ref(0)
let isActive = false
const items = ["A", "B", "C", "D"]
const selectItem = (i: number) => {
selectedItem.value = i
items.forEach((item, index) => {
return (isActive = item == items[index])
})
return selectedItem
}
return {
items,
selectedItem,
selectItem,
isActive,
}
},
})
</script>
Active a item inside a v-for loop when clicked
Your code has a couple problems:
- instead of
:style="panel.color"
, you should put in an object, so it should be:style="{ color: panel.color }"
- you forgot to add a click handler, i.e., you should add
v-on:click="..."
Note: To simplify things, I didn't use your getPanels
but use an array instead, it shouldn't affect how you understand how everything works.
const app = new Vue({ el: '#app', data: { panels: [ {section: 'One', action: 'Action 1', color: 'red' }, {section: 'Two', action: 'Action 2', color: 'blue' }, {section: 'Three', action: 'Action 3', color: 'green' }, {section: 'Four', action: 'Action 4', color: 'orange' }, {section: 'Five', action: 'Action 5', color: 'purple' } ], activeItem: -1 }, methods: { clickHandler(idx) { this.activeItem = idx } }});
.active { opacity: 0.7;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script><div id="app"> <div class="panel panel-default"> <ul class="list-group"> <li class="list-group-item" v-for="(panel, index) in panels" :class="{active: index === activeItem}" :style="{ color: panel.color }" v-on:click="clickHandler(index)" > A section {{panel.section}} was {{panel.action}} </li> </ul> </div>
</div>
setting one line item 'active' at a time in vue
You need to use a unique identifier to determine which comment is active. In the most rudimentary way using your current setup:
<li class="commentToggle"
v-bind:class="{active:commentActive === 'new'}"
v-on:click="setInputName('new')">
New Comment
</li>
<li class="commentToggle"
v-bind:class="{active:commentActive === 'note'}"
v-on:click="setInputName('note')">
Note
</li>
setInputName(str) {
this.inputName = str;
this.commentActive = str;
},
The adjustment that we made is to ensure that the commentActive
matches the str
that we've used. You can change that identifier to anything else, and pass additional arguments if you so choose.
How to put class="active" to first element in vuejs for loop
const TextComponent = {
template: `
<p>{{ text }}</p>
`,
props: ['text'],
};
new Vue({
components: {
TextComponent,
},
template: `
<div>
<text-component
v-for="(item, index) in items"
:class="{ 'active': index === 0 }"
:text="item.text">
</text-component>
</div>
`,
data: {
items: [
{ text: 'Foo' },
{ text: 'Bar' },
{ text: 'Baz' },
],
},
}).$mount('#app');
.active {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>
Vue: Set active class - get current DOM element
Something like this… ?
<div id="app">
<button :class="{'active': selected === 'a'}" @click="selected = 'a'">{{ message }}</button>
<button :class="{'active': selected === 'b'}" @click="selected = 'b'">{{ message }}</button>
<button :class="{'active': selected === 'c'}" @click="selected = 'c'">{{ message }}</button>
</div>
Demo: https://jsfiddle.net/6gxz9y8q/
You can also use watchers to detect when values are changed. (demo), or run function as you did like (demo) or (demo), but don't do something like (demo)
Related Topics
How to Format and Display Json Data Using Array.Map in Reactjs
Pdf Blob - Pop Up Window Not Showing Content
Npm Warn Enoent Enoent: No Such File or Directory, Open 'C:\Users\Nuwanst\Package.Json'
How to Read Data from *.Csv File Using JavaScript
Validate Phone Number With Yup
How to Get the Contextpath from Javascript, the Right Way
Write a Auto-Fill and Submit Web Form Program
Get Image from Json File Using JavaScript and Display in HTML Img Tag
Typescript Module Has No Exported Members - React
Reload Table After Deleting an Item from It With React
How to Split Date and Time from the Datetime Variable in JavaScript
Remove Time from Gmt Time Format
Hide Page Until Everything Is Loaded Advanced
Reactjs: Uncaught Referenceerror: Require Is Not Defined
Handle File Download from Ajax Post
How to Prevent a Key Input from Appearing in Input Field