簡體   English   中英

單擊鏈接並重定向時,如何添加活動類?

[英]How can I add class active when a link clicked and redirect?

我的 vue 組件是這樣的:

<template>
    <div>
        ...
        <div class="list-group">
            <a :href="baseUrl+'/message/inbox'" class="list-group-item">
                Message
            </a>
            <a :href="baseUrl+'/message/review'" class="list-group-item">
                Review
            </a>
            <a :href="baseUrl+'/message/resolution'" class="list-group-item">
                Resolution
            </a>
        </div>
        ...
    </div>
</template>
<script>
    export default {
        ...
        data() {
            return {
                baseUrl: window.Laravel.baseUrl
            }
        },
        ...
    }
</script>

單擊鏈接時,它將調用 url,我想在重新加載頁面后在單擊的鏈接上添加活動類。

但是,我仍然很困惑,我該怎么辦?

您可以添加一個計算屬性,例如currentPath

computed: {
  currentPath () {
    // grab current url and return the part after `baseUrl `
    // e.g. '/message/inbox' or '/message/review'
    return '/message/inbox'
  }
}

還有一個適合你特殊風格的 CSS 類:

.active-item {
  /* key-value pairs here */
}

然后在您的模板中,您可以將類應用於匹配的項目:

<a :href="baseUrl+'/message/inbox'"
   :class="{ 'active-item': currentPath === '/message/inbox'}">
   class="list-group-item">Message</a>
<a :href="baseUrl+'/message/review'"
   :class="{ 'active-item': currentPath === '/message/review'}">
   class="list-group-item">Review</a>

請閱讀有關使用對象語法綁定 HTML 類的文檔

添加到 Leo 的答案中,引入一個自動檢測是否處於活動狀態的組件是一個好主意,因此您不需要編寫一堆<a>元素和許多重復的屬性。

例如<custom-link>組件:

<custom-link href="/message/inbox" class="list-group-item">
  Message
</custom-link>
<custom-link href="/message/review" class="list-group-item">
  Review
</custom-link>
<custom-link href="/message/resolution" class="list-group-item">
  Resolution
</custom-link>

如果你不需要在其他組件中復用這個組件或者list-group-item類總是需要的,你也可以把這個類封裝到<custom-link>中。 它看起來會更干凈:

<custom-link href="/message/inbox">Message</custom-link>
<custom-link href="/message/review">Review</custom-link>
<custom-link href="/message/resolution">Resolution</custom-link>

custom-link的代碼如下所示:

<a
  :href="baseUrl + href"
  :class="{ active: isActive }"
  class="list-group-item"
>
  <slot></slot>
</a>

{
  props: ['href'],
  data: () => ({ baseUrl: window.Laravel.baseUrl }),
  computed: {
    isActive () {
      return location.href === this.baseUrl + this.href
    }
  }
}

我在這里直接使用location.href ,如果您需要一些計算來獲取當前 URL,您也可以使用像 Leo 的示例這樣的計算屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM