Vue.js-组件模板不使用v-for渲染

时间:2018-11-11 20:52:53

标签: vue.js vuejs2 vue-component

我有一种方法,它会向我的api调用ajax,并返回将我分配给数组的响应。之后,在带有v-for的模板部分中,我将显示数据。我更改了要显示的数据后,它仅渲染一次。刷新后,它不再显示。

控制台中没有错误,并且vue显示数组已填充返回的响应。

模板:

<template>
  <div class="row">
    <div class="col-12">
      <h5 class="component-title">Game board</h5>
      <button v-for="number in board" v-bind:key="number.results" :class="'col-1 btn btn-'+number.colors">{{number.positionToId}}</button>
    </div>
  </div>
</template>

脚本部分:

import RouletteApi from "@/services/api/Roulette";
export default {
  name: "GameBoard",
  data() {
    return {
      board: []
    };
  },
  created() {
    this.getBoardLayout();
  },
  methods: {
    getBoardLayout() {
      RouletteApi.getLayout().then(response => {
        //this.rLayout.orgResponse = response;
        for (var i = 0; i < response.slots; i++) {
          this.board[i] = {
            results: response.results[i],
            positionToId: response.positionToId[i],
            colors: response.colors[i]
          };
        }
      });
    }
  }
};

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

使用该方法填充数组没有反应,因此请使用push函数进行尝试:

methods: {
  getBoardLayout() {
    RouletteApi.getLayout().then(response => {
      //this.rLayout.orgResponse = response;
      for (var i = 0; i < response.slots; i++) {
        this.board.push({
          results: response.results[i],
          positionToId: response.positionToId[i],
          colors: response.colors[i]
        });
      }
    });
  }
}

或使用this.$set实例方法:

 methods: {
    getBoardLayout() {
      RouletteApi.getLayout().then(response => {
        //this.rLayout.orgResponse = response;
        for (var i = 0; i < response.slots; i++) {
          this.$set(this.board,i, {
            results: response.results[i],
            positionToId: response.positionToId[i],
            colors: response.colors[i]
          });
        }
      });
    }
  }