在做商城必不可少的功能就是在展示商品列表的时候,需要给用户一个按条件筛选的功能。
直接上代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue商品列表条件筛选案例,详细图文注释</title> <style> #app span{ padding: 3px; margin: 3px; cursor: default; } .red{ background: red; } i{ border: 3px solid red; background: gray; } </style> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.min.js"></script> </head> <body> <div id="app"> 当前选中的是: <span v-for="item,key in choose" :key="key">{{item}} <i @click="deleteOption(key)">X</i></span> <ul> <li v-for="(item,index) in dataList" :key="index"> <span>{{item.title}}</span> <span v-for="(option,i) in item.list" :key="i" @click="addChoose(option,index,i)" :class="{red:item.index==i}">{{option}}</span> </li> </ul> </div> <script> var cateData = [ { title:'品牌', list:['小米','华为','VIVO','OPPO'] }, { title:'尺寸', list:[4.0,5.4,6.0,6.6] }, { title:'系统', list:['Android','IOS','Window','HongMeng'] }, ] cateData.forEach(item=>item.index=-1) var vm = new Vue({ el:'#app', data:{ dataList:cateData, choose:{} }, methods: { addChoose(option,index,i){ if(this.choose[index]){ if(this.dataList[index].list[i]!=this.choose[index]){ //console.log("当前选择的值"+this.dataList[index].list[i]) //console.log("上一次选择的值:"+this.choose[index]) //console.log("替换") this.deleteOption(index) this.$set(this.choose,index,option) this.dataList[index].index=i }else{ //console.log("仅删除") this.deleteOption(index) } }else{ this.$set(this.choose,index,option) this.dataList[index].index=i } }, deleteOption(key){ this.$delete(this.choose, key) this.dataList[key].index=-1 } } }) </script> </body> </html>
文章评论