在Vue中使用v-for将行添加到一个表但不添加另一个表

时间:2017-08-15 14:38:49

标签: javascript html json for-loop vue.js

我需要在表#dynamic中添加行,但不应影响表static

如果我点击下面带代码的按钮,两个表都会更新,因为它们具有相同的v-for。并且,如果我在v-for中放置v-for,我的数据将无法获取。我无法弄清楚如何“独特”第一张桌子。

VUE / HTML:

<template>
  <table id="dynamic">
    <tr v-for="rows in list">
      <td>Content of row {{ rows.item1 }}</td>
      <td>Content of row {{ rows.item2 }}</td>
    </tr>
  </table>

  <div @click="block = !block">click</div>

  <table id="static">
    <tr v-for="rows in list">
      <td>Content of row: {{ rows.item3 }}</td>
      <td>Content of row: {{ rows.item4 }}</td>
    </tr>
  </table>
</template>

JS

export default {
  data: function () {
    return {
      list: [],
    };
  },
  props: ['channelId'],

  mounted() { },
  created() {
    this.fetchChannel(this.channelId);
  },
  methods: {
    fetchChannel: function (channelId) {
      $.getJSON('/api/channel/' + channelId, function (data) {
        this.list = data;
      }.bind(this));
    },
  }
}

我找到了一些帮助的示例,例如this codepenfiddle,但我没有成功。

1 个答案:

答案 0 :(得分:1)

如果#static表在其数据发生变化时真的永远不会更新,那么使用the v-once directive就是一种情况:

<table id="static" v-once>
  <tr v-for="rows in list">
    <td>Content of row: {{ rows.item3 }}</td>
    <td>Content of row: {{ rows.item4 }}</td>
  </tr>
</table>

这将告诉Vue只渲染一次表,然后在重新渲染时忽略它。

Here's a fiddle.