简体   繁体   中英

Vue JS - Dynamically add class to one element then remove class to siblings

I am new in using Vue.

I have a JS like this:

var app = new Vue({
    el: '#app',
    data: {
        nav1: true,
        nav2: false,
        nav3: false
    },
    methods: {
        activatedThis: function(n){
            if( n === 'nav2' )
            {
               this.nav1 = false;
               this.nav3 = false;
               this.nav2 = true;
            }
            else if( n === 'nav3' )
            //And so on...
        }
    }
});

HTML

<div id="app">
   <h1 @click="activatedThis('nav1')" v-bind:class="{ active: nav1 }">Navigation 1</h1>
   <h1 @click="activatedThis('nav2')" v-bind:class="{ active: nav2 }">Navigation 2</h1>
   <h1 @click="activatedThis('nav3')" v-bind:class="{ active: nav3 }">Navigation 3</h1>
</div>

I want to make my method dynamic.. I am thinking to loop the this . But since I don't know a lot about Vue yet... Is there a pure Vue way to this?

You can just change your code like following to make it more concise:

var app = new Vue({
    el: '#app',
    data: {
        navs: {
           nav1: true,
           nav2: false,
           nav3: false
        }
    },
    methods: {
        activatedThis: function(nav){
               this.navs.nav1 = nav === "nav1";
               this.navs.nav3 = nav === "nav2";
               this.navs.nav2 = nav === "nav3";
        }
    }
});

HTML:

<div id="app">
   <h1 v-for="(nav, index) in Object.keys(navs)" @click="activatedThis(nav)" v-bind:class="{ 'active': navs[nav] }">Navigation {{index}}</h1>
</div>

Related Links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM