I have the following code (vue v3.2.33)
<template v-for="route of routes" :key="route.name">
<li :set="open = false">
<div
@click="open = !open"
:>
</div>
</li>
</template>
Basically each li
has a collapse and opens with the class collapse-is-open
.
I tried to use a variable with the :set
attribute and modify that variable but it doesn't seem to work.
If that can't be working, what would be the other way of doing this ? An object based on the value I set in :key
that keeps track of all the states?
CodePudding user response:
:set
is syntax for the v-bind
directive. It binds a property/attribute on the element, but there is no such set
property for <li>
. I think you're trying to create an ad-hoc variable named open
for each <li>
, but that feature doesn't exist in Vue (perhaps you're thinking of petite-vue
's v-scope
).
One solution is to create a separate data structure that contains the open-state of each <li>
, and use that to update the class
binding:
export default {
data() {
return {
routes: [⋯],
open: {} // stores open-state of each route item
}
}
}
<template v-for="route of routes" :key="route.name">
<li>
<div
@click="open[route.name] = !open[route.name]"
:>
</div>
</li>
</template>
Alternatively, you could add that property to each array item in routes
:
export default {
data() {
return {
routes: [
{
name: 'Route 1',
open: false,
},
{
name: 'Route 2',
open: false,
},
{
name: 'Route 3',
open: false,
},
],
}
},
}
<template v-for="route of routes" :key="route.name">
<li>
<div
@click="route.open = !route.open"
:>
</div>
</li>
</template>