Vue.js toggle class on click

2019-01-16 15:57发布

How do you toggle a class in vue.js?

I have the following:

        <th class="initial " v-on="click: myFilter">
            <span class="wkday">M</span>
        </th>


        new Vue({
          el: '#my-container',

          data: {},

          methods: {
            myFilter: function(){

              // some code to filter users
            }
          }
        })

When I click th I want to apply active as a class as follows:

        <th class="initial active" v-on="click: myFilter">
            <span class="wkday">M</span>
        </th>

This needs to toggle i.e. each time its clicked it needs to add/remove the class.

How do you do this in vue.js?

8条回答
做个烂人
2楼-- · 2019-01-16 16:33

In addition to NateW's answer, if you have hyphens in your css class name, you should wrap that class within (single) quotes:

<th 
  class="initial " 
  v-on:click="myFilter"
  v-bind:class="{ 'is-active' : isActive}"
>

 <span class="wkday">M</span>
 </th>

See this topic for more on the subject.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-16 16:37

If you don't need to access the toggle from outside the element, this code works without a data variable:

<a @click="e => e.target.classList.toggle('active')"></a>
查看更多
登录 后发表回答