如何扩展 vue3 路由器中“router-link”的 onClick 处理程序行为

CMC*_*kai 3 vue.js vue-router

<router-link />想用它来导航到 Vue 3 应用程序中的另一个页面,但我还想在单击此链接时运行另一个函数。

现在我必须使用一个额外的<span />元素来包装<router-link />并添加@click属性以依赖事件冒泡。添加@click处理程序<router-link />会导致路由器链接不起作用,浏览器认为它只是一个普通的锚点 href。

    <span @click="handleClose(imageId)">
      <router-link
        :to="{name: 'image', params: {'imageId': imageId}}"
        class="permalink">
        Permalink
      </router-link>
    </span>
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

LeB*_*Ben 5

为了避免潜在的奇怪的并发错误(视图更改可能在调用您的方法之前发生,然后该方法将附加到未安装的组件),我将在您的方法中进行编程导航:

<template>
  <button type="button" @click="handleClose(imageId)">
    Permalink
  </button>
</template>

<script>
import router from '@/wherever/your/router/is/initialized';

export default {
  methods: {
    handleClose(imageId) {
      // Do your stuff
      router.push({ name: 'image', params: {'imageId': imageId}});
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)