vuejs實現新增tag標籤程式碼例項

zuoci_123456發表於2020-11-12
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}
.tag {
  width: 300px;
  height: 30px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding-left: 5px;
}
.btn {
  background-color: #008CFF;
  color: #fff;
  width: 100px;
  height: 32px;
  line-height: 32px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.taglist li {
  float: left;
  padding: 3px 10px;
  background-color: #2ECC71;
  border-radius: 5px;
  color: #fff;
  font-size: 20px;
  margin: 0 10px 0 0;
  cursor: pointer;
}
</style>
<script src="//cdn.bootcss.com/vue/2.1.6/vue.min.js"></script>
</head>
<body>
<div id="app">
  <p>Tag:
    <input type="text" class="tag" v-model="tag" /> 
    <input type="button" class="btn" v-on:click="add" value="提交" />
  </p>
  <div class="taglist">
    <ul>
      <li v-for="(tag,index) in taglist" v-on:click="del(index)">{{tag.tag}}</li>
    </ul>
  </div>
</div>
<script>
var vm = new Vue({
  el: "#app",
  data: {
    tag: "",
    taglist: [
    ]
  },
  methods: {
    add: function() {
      if (!this.tag || this.tag.trim() == "") {
        return false;
      }
  
      if (this.taglist.length > 0) {
        for (var i in this.taglist) {
          if (this.taglist[i].tag == this.tag) {
            return false;
          }
        }
      }
  
      if (this.taglist.length >= 10) {
        this.taglist.push({
          "tag": this.tag
        });
        this.taglist.splice(0, 1);
        this.tag = "";
      } else {
        this.taglist.push({
          "tag": this.tag
        });
        this.tag = "";
      }
    },
    del: function(index) {
      this.taglist.splice(index, 1);
    }
  }
})
</script>
</body>
</html>

 

相關文章