但是有router-link的话会出现1000多个组件,这不好,造成内存浪费,卡顿
用委托+编程式
<template lang="">
<!-- 商品分类导航 -->
<div class="type-nav">
<div class="container">
<h2 class="all">全部商品分类</h2>
<nav class="nav">
<a href="###">服装城</a>
<a href="###">美妆馆</a>
<a href="###">尚品汇超市</a>
<a href="###">全球购</a>
<a href="###">闪购</a>
<a href="###">团购</a>
<a href="###">有趣</a>
<a href="###">秒杀</a>
</nav>
<div class="sort">
<!-- //利用时间委派+编程式导航实现路由跳转和传递参数 -->
<div class="all-sort-list2" @click="goSearch">
<div class="item" v-for="(item,index) in categoryList" :key=item.categoryId
:class="{cur:currentIndex==index}">
<h3 @mouseenter="change(index)" @mouseleave="mouseleave">
<a :data-categoryName="item.categoryName" :data-category1Id="item.categoryId">{{item.categoryName}}</a>
</h3>
<!-- 二三级联动 -->
<div class="item-list clearfix" >
<div class="subitem" v-for="(subItem,index) in item.categoryChild"
:key="subItem.categoryId">
<dl class="fore">
<dt>
<a :data-categoryName="subItem.categoryName" :data-category2Id="subItem.categoryId">{{subItem.categoryName}}</a>
</dt>
<dd>
<em v-for="(subSubItem,index) in subItem.categoryChild"
:key="subSubItem.categoryId">
<a :data-categoryName="subSubItem.categoryName"
:data-category3Id="subSubItem.categoryId">{{subSubItem.categoryName}}</a>
</em>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {throttle} from "lodash"
import { mapState } from "vuex"
export default {
name: "TypeNav",
//组件挂碍完毕:可以向服务器发送求
mounted() {
console.log("nihao ");
this.$store.dispatch('categoryList');
},
data() {
return {
currentIndex: -1
}
},
computed: {
...mapState({
//右侧需要的是一个函数,当使用这个计算属性时,右侧函数会立即执行一次
//注入一个参数state,其实就是大仓库的数据
categoryList: state => state.home.categoryList
})
},
methods: {
// change(index) {
// console.log(_);
// },
//不用箭头函数,可能出现上下文this问题
change: throttle(function (index) {
//由于用户操作过快,浏览器解析逼过来,如果含有大量逻辑,就会卡顿
this.currentIndex = index
// console.log(index);
// console.log(this.currentIndex);
}, 30),
mouseleave() {
this.currentIndex = -1
},
goSearch(event){
//最好的决绝方案:编程式导航加事件委派
//问题:是吧全部节点,包括别的标签交给父节点
//单机a标签才跳转,怎么确定点击的是a标签?
//你能确定是a标签,怎么区分是1,2,3分级标签?
//第一个问题:在a中添加自定义属性,其余的没
this.$router.push("/search");
let element=event.target
// console.log(el);可以获得节点的信息
// console.log(e.target.dataset);
let {categoryname,category1id,category2id,category3id}=element.dataset
console.log(element.dataset);
if(categoryname){
//整理路由跳转参数
let location = {name:"search"};
let query = {categoryName:categoryname};
//123分类的a标签
if(category1id){
query.category1id=category1id;
}else if(category2id){
query.category2id=category2id;
} else {
query.category3id=category3id;
}
//整理完参数
location.query=query;
this.$router.push(location);
}
}
},
}
</script>
>