vue 过滤器的使用(解决forEach遇到的问题)

在学习过程中遇到了一个问题,本来我是想用forEach来解决的,但是一直报错

 

 

<template>
<div class="m-menu">
<dl class="nav">
<dt>全部分类</dt>
<dd v-for="item in menu" @mouseenter="ddEnter" :datatype="item.type">
<span class="arrow" >{{ item.name}}</span>
</dd>
</dl>
<div class="detail" v-if="kind"> //kind初始化为空,鼠标移入分类一节菜单的时候,赋值并展示
<template v-for="item in curDetail.child">
<h4>{{ item.title }}</h4>
<span v-for="spanItem in item.child">{{ spanItem }}</span>
</template>
</div>
</div>
</template>

<script>
export default {
name: "menuLeft",
data(){
return {
kind:'',
menu:[
{
type:'food',
name:'美食',
child:[{
title:'美食',
child:['代金券','甜点饮品','火锅','自助餐','小吃快餐']
}]
},
{
type:'takeout',
name:'外卖',
child:[{
title:'外卖',
child:['美团外卖']
}]
},
{
type:'hotel',
name:'酒店',
child:[{
title:'酒店星级',
child:['经济型','舒适/三星','高档/四星','豪华/五星']
}]
}
]
}
},
computed:{
curDetail:function () {

      //重要的问题在这里,最初我想通过forEach来拿到对应的数据,结果是数据拿到了,但是报错,就是我截图的那个错误,后来换了过滤器来解决就没有问题,
      查了很多资料也没有找到到底是什么原因造成的,初步感觉应该是执行效率的问题,但是找资料没有查到关于执行效率的资料
     
return this.menu.filter(item => item.type===this.kind)[0];

// this.menu.forEach((item)=>{
// if(item.type ==this.kind){
// return item //问题已找到,forEach方法无法返回数据造成的
// }
// })
}
},
methods:{
ddEnter(e){
this.kind = e.target.getAttribute('datatype'); //鼠标移入取到当前对象的datatype属性赋值给kind,在跟去kind去和menu中的数据进行匹配,来显示相对应的数据。
}
}
}
</script>

<style scoped>

</style>


最终效果图

 

posted @ 2019-08-30 14:21  hello树先生  阅读(8526)  评论(0编辑  收藏  举报