使用 vue-router 4 的点击方法

on click method with vue-router 4

使用 vue-router 3,可以在 router-link@click.native="myMethod" 上添加一个方法,就像 .

解释的那样

在 vue 3 中 .native 修饰符 was deprecated.

当用户点击 <router-link to="somewhere" @click="myMethod">Click me</router-link> 时, 它会导致整个应用程序重新加载的错误。

对于 vue-router 4,点击 router-link 标签时触发方法的正确方法是什么?

确保您的 vue-router 版本至少为 4.0.6(运行 npm show vue-routernpm 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>

Link to CHANGELOG