项目效果:
实现代码:
components/Category/index.vue
<div @mouseleave="leaveHandler">
<h2 class="all" @mouseenter="enterHandler" >
全部商品分类
</h2>
<!--商品分类结构-->
<transition name="sort">
<div class="sort" v-show="show">
<div class="all-sort-list2" @click="goSearch">
<!--item:代表一级分类 dl:代表二级 em:代表三级-->
<div class="item" v-for="(c1, index) in categoryArr" :key="c1.categoryId">
<h3 :class="{ active: index == currentIndex }" @mouseenter="changeIndex(index)">
<a :data-categoryName="c1.categoryName" :data-category1Id="c1.categoryId">
{{ c1.categoryName }}
</a>
</h3>
<div class="item-list clearfix" :style="{ display: index == currentIndex ? 'block' : 'none' }">
<div class="subitem">
<dl class="fore" v-for="(c2, index) in c1.categoryChild" :key="c2.categoryId">
<dt>
<a :data-categoryName="c2.categoryName" :data-category2Id="c2.categoryId">
{{ c2.categoryName }}
</a>
</dt>
<dd>
<em v-for="(c3, index) in c2.categoryChild" :key="c3.categoryId">
<a :data-categoryName="c3.categoryName" :data-category3Id="c3.categoryId">
{{ c3.categoryName }}
</a>
</em>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</transition>
</div>
methods: {
goSearch(event) {
//第一个:无法确定是否点击是a标签?
//第二个:无法获取路由跳转携带的参数?
//第三个:无法区分到底一级、二级、三级分类?
//dataset属性:DOM标签属性,获取标签自定义属性与属性值
let { categoryname, category1id, category2id, category3id } =
event.target.dataset; //切记大小写
//如果执行if条件语句点击的一定是a标签
if (categoryname) {
//路由跳转携带的参数
let option = {
name: "Search",
query: { categoryName: categoryname },
params: this.$route.params,
};
if (category1id) {
//整理参数:一级分类的id
option.query.category1Id = category1id;
} else if (category2id) {
option.query.category2Id = category2id;
} else {
option.query.category3Id = category3id;
}
console.log(option);
//路由跳转
this.$router.push(option);
}
},
},
实现思路:
1、事件委派,将事件委派给最近的父级
2、给a标签添加自定义属性,通过dataset属性(属于是DOM标签属性)获取标签自定义属性与属性值。