如何在单击链接并重定向时添加活动类?

时间:2017-03-30 05:32:16

标签: javascript vue.js vuejs2 vue-component

我的vue组件是这样的:

DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;WITH temp AS
(
   SELECT sd.*, row_number() OVER(ORDER BY (SELECT null)) - 1 AS RowIndex FROM @SampleData sd
)
,cte AS
(
   SELECT TOP 1  t.RowIndex, CAST( t.B_VOL  AS decimal(18,7)) AS sv FROM temp t ORDER BY t.RowIndex ASC
   UNION ALL
   SELECT t.RowIndex, CAST(cte.sv * (CASE WHEN t.RowIndex % 2 = 1 THEN CAST(1 AS decimal(18,7))/t.B_VOL ELSE t.B_VOL  END) AS  decimal(18,7)) AS sv                                 
   FROM  cte 
   INNER JOIN temp t ON cte.RowIndex + 1 = t.RowIndex 
)
SELECT  t.*, c.sv
FROM temp t
INNER JOIN cte c ON t.RowIndex = c.RowIndex
OPTION(MAXRECURSION 0)

点击链接后,它会调用网址,我想在重新加载页面后在点击的链接上添加活动类。

但是,我仍然感到困惑,我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以添加计算属性,例如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>

请阅读binding HTML classes with object syntax

上的文档

答案 1 :(得分:1)

根据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这样的计算属性。