美文网首页Vue
用Vue实现一个简单的队列增删功能

用Vue实现一个简单的队列增删功能

作者: awesome_lewis | 来源:发表于2017-08-11 17:58 被阅读16次

百度前端技术学院 - 任务十八
CodePen地址

任务描述

  • 模拟一个队列,队列的每个元素是一个数字,初始队列为空;
  • 有一个input输入框,以及4个操作按钮;
  • 点击"左侧入",将input中输入的数字从左侧插入队列中;
  • 点击"右侧入",将input中输入的数字从右侧插入队列中;
  • 点击"左侧出",读取并删除队列左侧第一个元素,并弹窗显示元素中数值;
  • 点击"右侧出",读取并删除队列右侧第一个元素,并弹窗显示元素中数值;
  • 点击队列中任何一个元素,则该元素会从队列中被删除
<div id="app">
  <input type="text" v-model="num">
  <button @click="insertNum('unshift')" :disabled="bool">左侧入</button>
  <button @click="insertNum('push')" :disabled="bool">右侧入</button>
  <button @click="removeNum('shift')" :disabled="bool1">左侧出</button>
  <button @click="removeNum('pop')" :disabled="bool1">右侧出</button>
  <hr>
  <span v-for="(item, index) in items" @click="items.splice(index, 1)">{{ item }}</span>
</div>
new Vue({
  el: "#app",
  props: ["disabled"],
  data: {
    num: "",
    bool: true,
    bool1: true,
    items: []
  },
  watch: {
    num() {
      this.num.trim() === "" ? (this.bool = true) : (this.bool = false);
    },
    items() {
      this.items.length === 0 ? (this.bool1 = true) : (this.bool1 = false);
    }
  },
  methods: {
    insertNum(method) {
      if (this.num.trim() === "") return;
      this.items[method](this.num);
      this.num = "";
      if (this.items.length > 0) {
        this.bool = false;
      }
    },
    removeNum(method) {
      this.items[method](this.num);
      if (this.items.length === 0) {
        this.bool = true;
      }
    }
  }
});

相关文章

网友评论

    本文标题:用Vue实现一个简单的队列增删功能

    本文链接:https://www.haomeiwen.com/subject/kxdklxtx.html