'How can I modify template variables declared with :set?
I have the following code (vue v3.2.33)
<template v-for="route of routes" :key="route.name">
<li :set="open = false">
<div class="collapse"
@click="open = !open"
:class="[open ? 'collapse-is-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?
Solution 1:[1]
: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 class="collapse"
@click="open[route.name] = !open[route.name]"
:class="[open[route.name] ? 'collapse-is-open' : '']">
</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 class="collapse"
@click="route.open = !route.open"
:class="[route.open ? 'collapse-is-open' : '']">
</div>
</li>
</template>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tony19 |
