一直在发博客,突然注意到在发布博客的时候选中对应的标签时的一个功能,最近一直在接触vue,于是想了一下要自己要怎么实现。
原图如下:
代码如下:
<template>
<div class="checkbox">
<h1>选中的ID值:{{checkboxValue}}</h1>
<div class="brame">
<span v-for="(item, index) in brameItem" :id="item.id">{{item.name}}<em @click="closebtn(item.id)">x</em></span>
</div>
<div class="label">
<label v-for="(item, index) in checkboxItem" >
<input type="checkbox" :value="item.id" :id="item.id" @click="addBrameItem(index)" v-model="checkboxValue">{{item.name}}
</label>
</div>
</div>
</template>
<script>
export default {
name: 'checkbox',
data (){
return {
checkboxValue: [], //存储checkbox选中的值
brameItem: [], //存储面包屑的值
checkboxItem: [{ //存储checkbox的值
'id': 1,
'name': 'CSS'
},{
'id': 2,
'name': 'JSP'
},{
'id': 3,
'name': 'JAVA'
},{
'id': 5,
'name': 'ECMA6'
},{
'id': 6,
'name': 'C#'
},{
'id': 7,
'name': 'C++'
},{
'id': 8,
'name': 'Oracle'
},{
'id': 9,
'name': 'Ruby'
}]
}
},
methods: {
//添加上面标签
addBrameItem (){
//console.log(this.checkboxItem[index]);
var event = event || window.event;
var target = event.target;
var id = target.id;
var _this = this;
var flag = false;
var obj = {};
//循环遍历面包屑对象,如果面包屑对象中存在一个对象id和点击的id一致,那么就不要追加到里面去了
_this.brameItem.forEach(function(item, index){
if(item.id == id){
flag = true; //已经存在id相等的值
//移出掉相等id的值
_this.brameItem.splice(index, 1);
}
});
//点击checkbox,面包屑中没有任何一个id与之对应
if(!flag){
obj.id = id;
obj.name = target.parentNode.innerText;
_this.brameItem.push(obj);
}
},
//点击面包屑删除小按钮
closebtn(id){
var _this = this;
console.log(id);
//去调checkbox对应id的选中状态
_this.checkboxValue.forEach(function(item, index){
if(id == item){
_this.checkboxValue.splice(index, 1);
}
});
//删除面包屑对应的id的模块
_this.brameItem.forEach(function(item, index){
if(id == item.id){
_this.brameItem.splice(index, 1);
}
});
}
}
}
</script>
<style scoped>
*{margin:0 auto;padding:0;font-family:"微软雅黑";}
.checkbox{
width:600px;
height:auto;
padding-bottom:10px;
}
.checkbox .brame{
padding:10px 0;
}
.checkbox .brame span{
display:inline-block;
padding:5px 15px;
margin:10px;
background:#ccc;
border:1px solid #ccc;
border-radius:20px;
}
.checkbox .brame span em{
display:inline-block;
width:20px;
height:20px;
margin-left:5px;
line-height:20px;
text-align:center;
font-style:normal;
color:#fff;
background:red;
border-radius:10px;
cursor:pointer;
}
.checkbox .label{
width:600px;
height:auto;
padding:20px 0 10px 0;
border:1px solid #ccc;
}
.checkbox .label label{
display:inline-block;
width:80px;
margin:20px;
}
.checkbox .label label input{
height:20px;
width:20px;
}
</style>
最终效果如下: