[Vuejs]-Vue: Updating Array with ID of Parent Cell

0👍

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue When you modify the length of the array, e.g. vm.items.length = newLength

For example:

var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})
vm.items[1] = 'x' // is NOT reactive
vm.items.length = 2 // is NOT reactive

To overcome caveat 1, both of the following will accomplish the same as vm.items[indexOfItem] = newValue, but will also trigger state updates in the reactivity system:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

Source
https://v2.vuejs.org/v2/guide/list.html#Caveats

Example
I havent tested this but should work

<script>
    export default {
        name: 'sudoku',
        data () {
            return {
                gameAnswer: [4, 3, 5, 2, 6, 9, 7, 8, 1, 6, 8, 2, 5, 7, 1, 4, 9, 3, 1, 9, 7, 8, 3, 4, 5, 6, 2, 8, 2, 6, 1, 9, 5, 3, 4, 7, 3, 7, 4, 6, 8, 2, 9, 1, 5, 9, 5, 1, 7, 4, 3, 6, 2, 8, 5, 1, 9, 3, 2, 6, 8, 7, 4, 2, 4, 8, 9, 5, 7, 1, 3, 6, 7, 6, 3, 4, 1, 8, 2, 5, 9],
                gameBoard: [4, 3, 5, 2, 6, 9, 7, 8, 1, 6, 8, 2, 5, 7, 1, 4, 9, 3, 1, 9, 7, 8, 3, 4, 5, 6, 2, 8, 2, 6, 1, 9, 5, 3, 4, 7, 3, 7, 4, 6, 8, 2, 9, 1, 5, 9, 5, 1, 7, 4, 3, 6, 2, 8, 5, 1, 9, 3, 2, 6, 8, 7, 4, 2, 4, 8, 9, 5, 7, 1, 3, 6, 7, 6, 3, 4, 1, 8, 2, 5, 9]
            }
        },
        methods: {
            randomNumber (index) {
                var val = Math.floor(Math.random() * 3)
                if (val === 0) {
                    this.$set(this.gameBoard, index, 0)
                    return true
                } else {
                    return false
                }
            },
            changeVal (index, number) {
                this.$set(this.gameBoard, index, number)
            }
        }
    }
</script>

<template>
    <div>
        <div class="wrapper"> 
            <div class="list"  v-for="(number,index) in gameAnswer" :key="index"> 
                <div  v-bind:id="index" class="cell-empty" v-if="randomNumber(index)"> 
                    <input type="text" v-on:keyup="changeVal( index, number)"> 
                </div>
                <div class="cell"  v-else> 
                    {{number}}  
                </div>
            </div>
            
            <div class="list" v-for="(number, index) in gameBoard" :key="index"> 
                {{number}} 
            </div>
            
            <div class="list" v-for="(number, index) in gameAnswer" :key="index"> 
                {{number}} 
            </div>
        </div>  
    </div>
</template>

Leave a comment