Vue数组内容未更新

时间:2020-06-08 14:36:15

标签: javascript vue.js

我想使用我创建的函数在此列表中添加一个数字,但是数据不会更新。 for循环将数据添加到列表中,但是上面的代码未使用它。

<script>
export default {
    data: () => ({
        row: [],
        column: [],
    }),
    methods: {
        async initGraph() {
            for(let x = 0; x < 25; x++)
            {
                this.row[x] = x;
                
            }
            for(let y = 0; y < 25; y++){
                this.column[y] = y;
            }
            console.log(this.row);
            console.log(this.column);
        }
    },
    mounted(){
        this.initGraph();
    } 
}
</script>
<template>
    <v-app>
        <tbody>
            <tr v-for="r in row" v-bind:key="r" :id="r">
                <td v-for="c in column" v-bind:key="c" :id="c" class="unvisited">
                </td>
            </tr>
        </tbody>
        <h1>{{row}}</h1>
    </v-app>
</template>

1 个答案:

答案 0 :(得分:0)

如果直接修改数组,Vue无法检测到对数组的更改。参见https://vuejs.org/v2/guide/list.html#Mutation-Methods 一种可能的解决方案是使用用于数组操作的方法。以下应该工作:

<script>
export default {
    data: () => ({
        row: [],
        column: [],
    }),
    methods: {
        initGraph() {
            for(let x = 0; x < 25; x++)
            {
                this.row.push(x);
                
            }
            for(let y = 0; y < 25; y++){
                this.column.push(y);
            }
            console.log(this.row);
            console.log(this.column);
        }
    },
    mounted(){
        this.initGraph();
    } 
}
</script>
<template>
    <v-app>
        <table>
          <tbody>
            <tr v-for="r in row" v-bind:key="r" :id="r">
              <td v-for="c in column" v-bind:key="c">{{c}}</td>
            </tr>
          </tbody>
        </table>
    </v-app>
</template>