首页 > 解决方案 > Vue 数组内容没有更新

问题描述

我想使用我创建的函数向此列表添加一个数字,但是数据不会更新。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>

标签: javascriptvue.js

解决方案


如果直接修改数组,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>


推荐阅读