vuejs / composition-api

Composition API plugin for Vue 2
https://composition-api.vuejs.org/
MIT License
4.19k stars 343 forks source link

Reactivity in v-for does not work #928

Closed brolnickij closed 2 years ago

brolnickij commented 2 years ago

Problem

Solving a trivial problem, using @vuejs/composition-api, I came across a reactivity problem in v-for, namely

<template>
  <div 
    v-for="(item, itemIndex) in items" 
    :key="itemIndex"
  >
    <p v-if="states[itemIndex]">{{ item.name }}</p>
    <button @click="onSwitch(itemIndex)">switch</button>
  </div>
</template>

<script setup>
  const items = ref([
    { name: "test" },
    { name: "test 1" },
    { name: "test 2" },
    { name: "test 3" }
  ])
  const states = ref(new Array(items.value.length).fill(false))

  // when changing value (states.value[index]), reactivity does not work
  function onSwitch(index) {
    states.value[index] = !states.value[index]
  }
</script>

Examples

Vue.js 3 | work Vue.js 2 + vuejs/composition-api | doesnt work

--

P.S. many thanks to the vue.js team for developing this wonderful tool

jacekkarczmarczyk commented 2 years ago

https://v2.vuejs.org/v2/guide/reactivity.html?redirect=true#For-Arrays

LinusBorg commented 2 years ago

we provide set and delete helpers for this:

import { set } from '@vue/composition-api'
// ...
set(states.value, index, !states.value[index])
brolnickij commented 2 years ago

@LinusBorg was unaware that @vue/composition-api provided these methods

thank you!

--

P.S. for those using @nuxtjs/composition-api + unplugin-auto-import + unplugin-vue2-script-setup, you will have to explicitly import the dependency

import { set, del } from '@nuxtjs/composition-api'