首页 > 解决方案 > 使用 Vue 触发链接内的按钮

问题描述

我有一组图像,其中包含一些信息,例如作者,现在我添加了一些按钮以允许用户喜欢图像。

由于图像具有指向图像屏幕的链接,我不知道如何触发按钮以避免触发链接。

这是代码,我使用的是 Vuetify 和 Nuxt:

<nuxt-link
  :to="
    `/photo/${slotProps.item.id}/${
      slotProps.item.slug
    }`
  "
>
  <v-hover>
    <v-img
      slot-scope="{ hover }"
      :src="slotProps.item.url"
    >
      <v-fade-transition mode="in-out">
        <div
          v-if="hover"
          class="d-flex transition-fast-in-fast-out photo-overlay pa-2"
        >
          <div
            class="d-flex pl-1 credits justify-space-between align-center w-100"
          >
            <div>
              <nuxt-link
                :to="
                  `/user/${slotProps.item.pId}`
                "
                class="secondary--text body-2 d-inline-block"
              >
                <v-avatar size="30">
                  <img
                    :src="slotProps.item.avatar"
                    :alt="`${slotProps.item.name}`"
                  />
                </v-avatar>
                <span class="ml-2">
                  {{ slotProps.item.name }}
                </span>
              </nuxt-link>
            </div>
            <div>
              <v-menu
                v-model="addToGalleriesMenu"
                :close-on-content-click="false"
                :nudge-width="200"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-btn v-on="on" v-bind="attrs" icon color="secondary">
                    <v-icon small>
                      fal fa-hearth
                    </v-icon>
                  </v-btn>
                </template>
                <v-card outlined>
                  <v-card-title>Test</v-card-title>
                </v-card>
              </v-menu>
            </div>
          </div>
        </div>
      </v-fade-transition>
    </v-img>
  </v-hover>
</nuxt-link>

上面的代码生成一个图像,鼠标悬停在底部会出现一个图层,显示名称和一个按钮来喜欢图像。

正如预期的那样,单击用户链接可以正常工作。单击应该触发操作的按钮不起作用,因为单击了图像链接。

我该如何解决它?

标签: javascriptvue.jsnuxt.jsvuetify.js

解决方案


您可以使用 Vue 点击修饰符非常轻松地停止事件传播到父元素:

<a href="example.com">
  ...  
  <v-btn @click.stop.prevent="test()">
   ...

您可以在不使用 Vue 修饰符的情况下实现相同的目的:

<a href="example.com">
  ...  
  <v-btn @click="test($event)">
   ...
methods: {
  test (event) {
    event.preventDefault()
    event.stopPropagation()
  }
}

推荐阅读