一、报错
二、报错原因
重复路由跳转。因为点击事件执行了两次,造成了路由重复跳转。
<template>
<div>
<div class="search">
<input type="text" v-model="keyword" placeholder="请输入城市名或拼音" class="search-input">
</div>
<div class="search-content" ref="search" v-show="keyword">
<ul>
<li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="changeCity(item.name)">{{item.name}}</li>
<li class="search-item border-bottom" v-show="noData">未找到匹配数据</li>
</ul>
</div>
</div>
</template>
三、解决方案
1、网上转烂的一种,有效
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
return originalPush.call(this, location).catch(err => err)
}
修改文件:router/index.js
点击事件还是执行了两次,只是上边的代码将错误信息进行了捕获,不报错了而已。
2、升级vue-router版本(亲测无效)
3、@click="changeCity(item.name) 写成 @click.native="changeCity(item.name)
报错:v-on的.native修饰符仅对组件有效,但是你在<li>上使用了它
4、 @click="changeCity(item.name) 写成 @click.stop="changeCity(item.name) (亲测无效)
5、 @click="changeCity(item.name) 写成 @click.once="changeCity(item.name) 有效
注意:虽然路由地址不会重复点击,但是该链接只能点击一次,点击后再点击不会响应。
6、通过 setTimeout 有效、推荐
export default {
data () {
return {
time: null
}
},
methods: {
changeCity (city) {
if (this.timer) {
clearTimeout(this.timer)
}
this.time = setTimeout(() => {
console.log(city)
this.$store.dispatch('changeCites', city)
this.$router.push('/')
}, 24)
}
}
}
第六种方法是最近学到的可以提升性能的一种方式,常用语 touch、click 操作频繁时。
以上。