How do I pass a variable from a v-bind:class in the template HTML to the component method?

时间:2019-04-16 23:00:46

标签: javascript function class for-loop vue.js

I want my navbar to apply a different style to the current page.

I've built a component that loops through each link. Within the loop I want to pass the current link's url to a method that will check if the current page url is the same as the url of the link. If it is the new style will be applied.

component.js

module.exports = {
  data: function() {
    return {
      links: [
        {name: 'Projects', url: "/admin"},
        {name: 'Archives', url: "/archives"},
        {name: 'Information', url: "/information/1/edit"},
        {name: 'Footer', url: "/footer/edit"},
      ]
    }
  },
  computed: {
    currentPage: {
      get: function() {
        return window.location.pathname
      }
    },
    activePage: {
      get: function() {
        this.links.forEach((item) => {
          item.currentpage = this.currentPage
          item.active = false
          if (item.url === item.currentpage) { item.active = true}
        })
      }
    }
  }
}

component.html

<ul v-for="link in this.links">
  <li>
    <a :href="link.url" :class="{active: link.active}">{{link.name}}</a>
  </li>
</ul>

1) I can't pass a variable from :class to the component computed property or method.
2) In the current scheme, the component renders the array with only one link with the property {active: true}. Yet still the :class won't respond to this.

0 个答案:

没有答案