在vue-router 3中,可以使用@click.native="myMethod"在router-link上添加方法,就像解释here一样。
在vue 3中,.native修饰符was deprecated。
当用户点击<router-link to="somewhere" @click="myMethod">Click me</router-link>时,就会产生一个bug,整个应用程序都会重新加载。
使用vue-router 4,在点击router-link标签时触发方法的正确方式是什么?
发布于 2021-04-08 07:32:15
确保您的vue-router版本至少为4.0.6 (运行npm show vue-router或npm outdated)。在该版本中,有一个修复程序,允许您执行您想要实现的操作。基本上,你问题中的这段代码现在应该可以工作了。
就像这样:
<template>
<router-link to="/somePath" @click="myMethod()">Click me</router-link>
</template>
<script>
export default {
methods: {
myMethod() {
console.log('hello');
}
}
}
</script>以下是Vue 3和最新的vue路由器4的可运行代码片段
const App = {
template: `
<div class="wrapper">
<router-view />
<router-link to="/hello" @click="myMethod()">Link (click me)</router-link>
Did my method run: {{didMyMethodRun}}
</div>
`,
data() {
return {
didMyMethodRun: false,
}
},
methods: {
myMethod() {
this.didMyMethodRun = true
}
}
}
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{path: '/', component: {template: 'You are now on default route'}},
{path: '/hello', component: {template: 'You are now hello route'}},
]
})
const app = Vue.createApp(App);
app.use(router)
app.mount('#app');.wrapper {
display: flex;
flex-direction: column;
}<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<html>
<body>
<div id="app"/>
</body>
</html>
https://stackoverflow.com/questions/66911113
复制相似问题