I am using v-for
to render a list based on an array of objects.
<ul>
<li v-for="category, i in categories"
:class="{active: category.active}"
@click="changeCategory(i)">
<a>{{ category.service_type_name }}</a>
</li>
</ul>
When you click the list item changeCategory(index)
runs:
changeCategory(index) {
this.categories.forEach((c, i) => {
c.active = (i != index)? false : true
})
}
So the clicked-on list items active
attribute gets set to true
and all others set to false
, and the list item gets an .active
class added to it (because of the :class="{active: category.active}"
line in the template.
However, the DOM is not updated to show this change.
Is there anyway to update the DOM automatically when this change occurs, without using this.$forceUpdate()
in the changeCategory(index)
function?
edit: changed map
to forEach
, DOM still does not update.
edit: I am using vue-class-components with typescript
import Vue from 'app/vueExt'
import { Component } from 'vue-property-decorator'
import * as Template from './services.vue'
@Component({
mixins: [Template]
})
export default class Services extends Vue {
categories = []
created() {
this.api.getServiceSetupCatagories().then((res) => {
this.categories = res.categories
this.categories.forEach((c, i) => {
// adding active property to the object
// active = true if i = 0, false otherwise
c.active = (i)? false : true
})
})
}
changeCategory(index) {
this.categories.forEach((c, i) => {
c.active = (i != index)? false : true
})
}
}
map
doesn't modify your array, it returns a new array. Therefore vue doesn't detect any change and your dom isn't updated. Try usingforEach
instead. – TuscanforEach
and event went to the extent of using afor
loop to changeactive
property, but it had no effect. When Iconsole.log
the item it shows the correctactive
value, but the DOM doesn't get updated. – Flourishmap
function instead offorEach
and that works too as intended. I am not sure why the DOM isn't updating in my case. – Flourishactive
property beforehand? – Kabyleactive
property does not exist oncategory
until thechangeCategory
method is called, then you are falling into a caveat in Vue and should useVue.set(c, "active", i != index ? false : true)
. vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats – Kabylecreated()
hook). Still no effect. – Flourish