Vue.js: Router-link 里面有一个函数

Vue.js: Router-link with a function inside

我的应用程序中有来自 API 的通知。每个通知都有一个参数 "notification_type"。通过点击通知,用户可以根据 notification_type 被定位到具有不同内容的不同页面。在通知的组件中,我有路由器 link,它必须指向不同的组件(用户页面)。

<template>
 <div>
  <router-link to="/#">
    <p>
    <span v-html="item.message"></span>
    </p>
  </router-link>
 </div>
</template>

<script>
export default {
   props: ['item']
}
</script>

我认为我需要传递一个带条件的函数,而不是“/#”。例如,如果 notification_type 等于 "user_subscribed",则用户将被定向到关注者的页面。如果 notification_type 等于 "comment_created",那么用户将被发送到带有评论的 post 页面。我理解逻辑,但我正在努力实现这一点。

你可以这样实现:

<template>
 <div @click="redirectUser(item.notification_type)">
    <p>
    <span v-html="item.message"></span>
    </p>
 </div>
</template>

<script>
export default {
   props: ['item'], 
   methods: {
     redirectUser (notificationType) {
       if (notificationType === 'user_subscribed') {
         this.$router.push('/your-custom-route')
       } else if (notificationType === 'comment_created') {
         this.$router.push('/awesome-comments')
       }
     }
   }
}
</script>