简体   繁体   English

使用 vue-router 4 的点击方法

[英]on click method with vue-router 4

With vue-router 3, it was possible to add a method on router-link with @click.native="myMethod" like explained here .使用 vue-router 3,可以使用@click.native="myMethod"router-link上添加一个方法,就像在此处解释的那样。

In vue 3 the .native modifier was deprecated .在 vue 3 中, 不推荐使用.native修饰符。

When a user clicks on <router-link to="somewhere" @click="myMethod">Click me</router-link> , it creates a bug where the entire app reloads.当用户点击<router-link to="somewhere" @click="myMethod">Click me</router-link>时,它会在整个应用程序重新加载时创建一个错误。

With vue-router 4 , what is the correct way to trigger a method on click on a router-link tag?使用vue-router 4 ,触发单击router-link标签的方法的正确方法是什么?

Make sure your vue-router version is at least 4.0.6 (run npm show vue-router or npm outdated ).确保您的vue-router版本至少为 4.0.6(运行npm show vue-routernpm outdated )。 In that version, there's a fix that allows doing what you're trying to achieve.在那个版本中,有一个修复程序可以让你做你想做的事情。 Basically, the piece of code in your question should just work now.基本上,您问题中的那段代码现在应该可以工作了。

So like:就像:

<template>
  <router-link to="/somePath" @click="myMethod()">Click me</router-link>
</template>
<script>
export default {
  methods: {
    myMethod() {
      console.log('hello');
    }
  }
}
</script>

Here's a runnable snippet with Vue 3 and the newest vue router 4这是 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 链接到变更日志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM