代码之家  ›  专栏  ›  技术社区  ›  Alex Druzenko

如何在范围更改Vuejs时更新v-for

  •  0
  • Alex Druzenko  · 技术社区  · 3 年前

    我正在尝试使用一个按钮,当单击时可以添加组件的其他副本,我能想到的最好方法是循环浏览一个范围并更新该范围。下面是我尝试过的。

           <Component v-for="index in count" :key="index"/>
          <button @click="count++">Add Component</button>
    

    然而,这是不起作用的,因为当计数正确更新时,添加组件不会出现。我不知道如何解决这个问题,甚至不知道这是否是我想做的事情的正确方式。我也试过 this.$forceUpdate() 没有运气。任何援助都是有益的。

    非常感谢。

    0 回复  |  直到 3 年前
        1
  •  2
  •   bsatprivat    3 年前

    使用 ref 对于 counter

    https://vuejs.org/guide/essentials/template-refs.html#refs-inside-v-for

    <script setup>
    import { ref } from 'vue'
    
    const counter = ref(1)
    </script>
    
    <template>
      <div v-for="index in counter">
        Component
      </div>
      <button @click="counter++">Add Component</button>
    </template>
    
    推荐文章