在行数达到一定限制后隐藏行

时间:2019-05-07 19:54:12

标签: vue.js

我对编码非常陌生,但对Java却非常了解。我创建了一个表,该表将在单击按钮时将更新推送到我的表。但是,我确实想限制表中的行数。例如说在将第六个数据推送到表时,我确实希望从该行中删除第一个数据。

我尝试在任何地方都没有运气。也许是因为我对javascript的基本了解非常基础。我是新手哈哈。我正在为此代码使用vue.js。

HTML

<form class="form-inline">
    <div class="form-group mx-sm-3 mb-2">
           <input 
        type="number"  
        v-model="newElement.buy" 
                class="form-control">
    </div>
    <button 
        v-on:click="buyStock" 
        type="button" 
        class="btn btn-success mb-2">BUY
</button>
</form>

<section class="stock_tables">  
<table class="table table-striped">
 <thead>
  <tr>
    <th scope="col">{{codeBuy}}</th>
    <th><a v-html="negative"></a> Buy</th>
  </tr>
 </thead>
 <tbody>
  <tr v-for="u in stocks">
    <th></th>
      <td>{{u.buy}}</td>
  </tr>
 </tbody>
</table>
</section>

脚本

<script>
new Vue({
  el: '#app',
    data: {
       codeBuy: "12345",
       stocks: [],
       newElement: {buy:"",sell:""}
  },
  methods: {
      buyStock: function(){
      this.stocks.push({buy:this.newElement.buy});
      this.newElement = {buy:""};
      }
   }
});
</script>


因此,基本上,每次我输入库存数量并按买入时,它将更新。

1 个答案:

答案 0 :(得分:0)

您可以通过一些选项来修改buyStock方法:

  • this.stocks.shift()
  • this.$delete(this.stocks, 0)
  • this.stocks = this.stocks.slice(1);
  • this.stocks = this.stocks.slice(-5);
  • this.stocks = this.stocks.splice(0, 1);

或者,没有if的使用:

this.stocks = [...this.stocks, {
  buy: this.newElement.buy
}].slice(-5);

下面的演示:

new Vue({
  el: '#app',
  data: {
    codeBuy: "12345",
    stocks: [],
    newElement: {
      buy: "",
      sell: ""
    },
    negative: ''
  },
  methods: {
    buyStock: function() {
      this.stocks.push({
        buy: this.newElement.buy
      });
      if (this.stocks.length > 5) {
        // this.$delete(this.stocks, 0);
        // this.stocks = this.stocks.slice(1);
        // this.stocks = this.stocks.slice(-5);
        // this.stocks = this.stocks.splice(0, 1);
        this.stocks.shift();
      }
      //this.stocks = [...this.stocks, {
      //  buy: this.newElement.buy
      //}].slice(-5);
      this.newElement = {
        buy: ""
      };
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <form class="form-inline">
    <div class="form-group mx-sm-3 mb-2">
      <input type="number" v-model="newElement.buy" class="form-control">
    </div>
    <button v-on:click="buyStock" type="button" class="btn btn-success mb-2">BUY</button>
  </form>

  <section class="stock_tables">
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">{{codeBuy}}</th>
          <th><a v-html="negative"></a> Buy</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="u in stocks">
          <th></th>
          <td>{{u.buy}}</td>
        </tr>
      </tbody>
    </table>
  </section>
</div>