[英]on click method with vue-router 4
使用 vue-router 3,可以使用@click.native="myMethod"
在router-link
上添加一个方法,就像在此处解释的那样。
在 vue 3 中, 不推荐使用.native
修饰符。
当用户点击<router-link to="somewhere" @click="myMethod">Click me</router-link>
时,它会在整个应用程序重新加载时创建一个错误。
使用vue-router 4 ,触发单击router-link
标签的方法的正确方法是什么?
确保您的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.