![](/img/trans.png)
[英]Vue.js: How to prevent browser from going to href link and instead only execute the @click method?
[英]Vue.js @click not execute function when a:href link is exist
我正在尝试创建通知,当点击通知并链接到他的路径时,通知长度会减少。
<li class="header">You have {{ notificationsCount()}} notif</li> <li>
<ul class="menu">
<li v-for="(notification, index) in notif" :notification="notification" :key="notification.id">
<a :href="notification.data.path"
@click="markAsRead(notification.id)"
@mouseup.right="markAsRead(notification.id)"
class="text-aqua">{{ notification.data.message }}
</a>
</li>
</ul>
methods: {
notificationsCount() {
return this.notif.length
},
markAsRead(index, id) {
if (this.notif.length){
axios.delete(`/notifications/${id}`)
.then(() => {
this.notif.splice(index, 1);
this.notificationsCount();
});
}
}
}
问题是当存在 :href 链接时,notificationcount 不会减少,但是当 :href 填充为 (#) 或我使用 @click.prevent 执行函数时,notificationcount 会减少。 如何解决?
在标签内,我有两个触发器 @click 和 @mouseup.right 在打开新标签时用于处理。 当我点击它的工作正常并且通知减少,因为通过@mouseup.right 执行但是当通过@click 执行时它不起作用。 我必须再次重新加载以减少通知计数
这按预期工作。 您可以在计数器离开之前看到它的变化。 当您离开该页面时,程序将被擦除。 当您返回该页面时,它会重新启动。 如果您希望数据值持久化,您将需要使用某种持久存储,如localStorage
或数据库。 你有 axios,但我不能在我的例子中使用它。
跟随另一个页面的链接将卸载当前页面,因此您没有太多机会看到更改发生。 此外,您没有正确找到要拼接的项目。
new Vue({ el: '#app', data: { notif: [{ id: 1, data: { path: 'http://www.google.com', message: 'Go to google' } }] }, computed: { notificationsCount() { return this.notif.length; } }, methods: { markAsRead(item) { const index = this.notif.indexOf(item); this.notif.splice(index, 1); } } });
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script> <div id="app"> Count: {{notificationsCount}} <ul class="menu"> <li v-for="(notification, index) in notif" :key="notification.id"> <a :href="notification.data.path" @click="markAsRead" class="text-aqua">{{ notification.data.message }} </a> </li> </ul> </div>
您的问题是 axios 请求尚未完成,页面已重定向到该路径。 你可以在 axios 请求完成后重构重定向功能。
...
<a
@click="markAsRead(notification)"
@mouseup.right="markAsRead(notification)"
class="text-aqua">{{ notification.data.message }}
</a>
...
markAsRead(index, notification) {
if (this.notif.length){
axios.delete(`/notifications/${id}`)
.then(() => {
this.notif.splice(index, 1);
this.notificationsCount();
window.location = notification.data.path
});
}
}
您不需要将 click 和 mouseup 绑定在一起,选择 click 或 mouseup。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.