确保您的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>
链接到变更日志