在很多的电商项目当中,都会有底部导航的切换,需要用到点击事件,在这里,我用的是Vue的框架来说明。
1、这里是@click的用法(这是在组件中的写法)
<template>
<div>
<router-view /><!-- 路由中用来展示的 -->
<div class="xps_footer">
<router-link to="/" :class="sel == '/' ? 'red' : 'back' " @click="selectNav">
<div>
<span class="iconfont icon-shouye xps_icon"></span>
<div>首页</div>
</div>
</router-link>
<router-link to="/classify" :class="sel == '/classify' ? 'red' : 'back' " @click.="selectNav">
<div>
<span class="iconfont icon-fenlei xps_icon"></span>
<div>分类</div>
</div>
</router-link>
<router-link to="/cart" :class="sel == '/cart' ? 'red' : 'back' " @click="selectNav">
<div>
<span class="iconfont icon-gouwuche1 xps_icon"></span>
<div>购物车</div>
</div>
</router-link>
<router-link to="/myself" :class="sel == '/myself' ? 'red' : 'back' " @click="selectNav">
<div>
<span class="iconfont icon-yonghuzhongxin xps_icon"></span>
<div>我的</div>
</div>
</router-link>
</div>
</div>
</template>
<script>
export default {
data(){
return {
sel:window.location.pathname //默认被选中的那一个导航,根据路由显示
}
},
methods:{
selectNav(){
console.log(window.location.pathname)
this.sel = window.location.pathname;
}
}
};
</script>
<style>
.back {
color: #000000;
}
.red {
color: red;
}
body {
margin: 0;
padding: 0;
}
.xps_Header {
width: 100%;
height: 50px;
color: white;
font-size: 20px;
text-align: center;
line-height: 50px;
background-color: orangered;
position: fixed;
top: 0;
}
.xps_footer {
width: 100%;
height: 60px;
display: flex;
justify-content: space-around;
flex-direction: row;
align-items: center;
position: fixed;
bottom: 0;
border: 1px solid #999;
font-size: 20px;
}
.xps_icon {
font-size: 25px;
margin-left: 6px;
}
a {
text-decoration: none;
}
</style>
<router-link to="/classify" :class="sel == '/classify' ? 'red' : 'back' " @click.="selectNav">
在这里当点击首页、分类、购物车和我的的时候,@click
事件不可以执行。
那解决办法就是在@click
后面加上一个修饰符.native
就可以在router-link
中使用点击事件。
native是什么?
.native
- 监听组件根元素的原生事件。
主要是给自定义的组件添加原生事件。
具体怎么用,看下面:
<router-link to="/classify" :class="sel == '/classify' ? 'red' : 'back' " @click.native="selectNav">
<div class="xps_footer">
<router-link to="/" :class="sel == '/' ? 'red' : 'back' " @click.native="selectNav">
<div>
<span class="iconfont icon-shouye xps_icon"></span>
<div>首页</div>
</div>
</router-link>
<router-link to="/classify" :class="sel == '/classify' ? 'red' : 'back' " @click.native="selectNav">
<div>
<span class="iconfont icon-fenlei xps_icon"></span>
<div>分类</div>
</div>
</router-link>
<router-link to="/cart" :class="sel == '/cart' ? 'red' : 'back' " @click.native="selectNav">
<div>
<span class="iconfont icon-gouwuche1 xps_icon"></span>
<div>购物车</div>
</div>
</router-link>
<router-link to="/myself" :class="sel == '/myself' ? 'red' : 'back' " @click.native="selectNav">
<div>
<span class="iconfont icon-yonghuzhongxin xps_icon"></span>
<div>我的</div>
</div>
</router-link>
</div>
使用native的原因主要有两点: