如何在vueJS中重新初始化v-for组件

问题描述 投票:0回答:2

我的vuejs项目中有一个数组。我用v-for在我的HTML文件中渲染该数组。然后通过检查条件从该呈现的模板中删除一些元素。当我想重新初始化该数组并重新呈现时,它并没有呈现该数组的所有元素。它正在跳过已删除的元素。但是,我想初始化它们。

这是我的代码:

            <div class="playground">

                <button @click="checkSort($event.target);" v-for="num in numArray" :value="num">
                    {{num}}
                </button>

            </div>

这是checkSort函数,用于从数组中删除元素。

        checkSort: function name(e) {
            let indexOfArr = this.numArray[this.index]

            if (indexOfArr == e.value) {
                console.log('milse')
                if (this.index == this.numArray.length - 1) {
                    console.log('full')
                    this.score += 100
                    this.numArray = null
                    this.numArray = this.generateUniqueArray(6, 40)
                    this.index = 0
                }
                this.score += 20
                this.index++
                e.remove()
            } else {
                this.numArray = this.generateUniqueArray(6, 40)
                this.index = 0
            }
        },

第一次在数组初始化时,它看起来像:[1,2,3,4,5,6]我要删除数组中的所有数字,然后删除所有数字,然后尝试用一些新数字重新生成一个新数组,并生成该数组,但它并不能使用所有新数字进行渲染。

javascript vue.js vuejs2 vue-component
2个回答
0
投票
  1. 即使数组开始为空,也请确保在data属性中初始化数组:
data: {
  numArray: [],
}
  1. 总是为数组中的每个值分配一个绑定key
<button
  @click="checkSort($event.target);"
  v-for="(num, index) in numArray"
  :value="num"
  :key="index"
>
  {{num}}
</button>

0
投票

我用拼接方法解决了。我通过拼接功能删除了一个项目,当数组为空时,它会由函数自动初始化

        checkSort: function (e) {
            let valueOfIndex = this.numArray[0]

            if (valueOfIndex == e.value) {
                if (0 == this.numArray.length - 1) {
                    this.score += 100
                    this.numArray = this.generateUniqueArray(6, 40)
                    this.shuffledArray = this.shuffle(this.numArray)
                }
                this.score += 20
                this.numArray.splice(0, 1)
            } else {
                this.numArray = this.generateUniqueArray(6, 40)
                this.shuffledArray = this.shuffle(this.numArray)
            }
        },
© www.soinside.com 2019 - 2024. All rights reserved.