gaurav_rajput
gaurav_rajput

Reputation: 101

Vue watch does not run when the property being watched is not changed on page reload

<template>
<!-- The navbar has a property for gender, the color of the navbar will change depending on the 
 gender -->
<!-- pass the props gender through a form submission and event -->

<div class="nav-main" :class="{female: isGirl, male: isBoy}">
  <nav class="menu">
      <a href="#">Home</a>
      <a href="#">Find</a>
      <a href="#">Match</a>
  </nav>
  <nav class="settings">
      <a href="#" class="setting-link">Settings</a>
  </nav>
</div>
</template>

<script>

export default {
 name: 'Navbar',
 props: ['gender'],
 data(){
    return{
        isBoy: false,
        isGirl: false,
    }
 },
 watch: {
    gender: function(){
        if(this.gender === 'male'){
            this.isGirl = false
            this.isBoy = true
            return 0
        }else{
            this.isBoy = false
            this.isGirl = true
            return 0
        }
    }

 }
 }

 </script>

 <style scoped>
 .nav-main{
    padding: 20px 0;   
    display: grid;  
    
  }
 nav{
    display: inline-block;
 }
 .menu{
    grid-column: 1/4;
    text-align: right;
 }
 .settings{
    grid-column: 4/6;
    text-align: right;
 }
 a{
    color: white;
    text-decoration: none;
    padding: 0  50px;
    font-family: 'Nunito', sans-serif;
 }
 .female{
    background: #ffb6c1;
}
.male{
    background: #4169e1;
}
</style>

What i am planning to do is if the value passed in the property 'gender' is male then the class male is applied on the navbar but if anything other then class female will be applied this is working fine and well and whenever i change the property the things go just as planned but whenever i reload the page the watch function does not trigger and the value remains unchanged why is this happening and how can i solve it.

like for say if i pass the prop as male then the male class is applied and if i change the prop to female then female change is applied but now if i reload the page then nothing happens

Upvotes: 2

Views: 700

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

The recommended pattern in your case is the computed properties, change isBoy isGirl to computed properties based on gender prop :

props: ['gender'],

computed: {
    isBoy() {
         return this.gender==='male'
    },

    isGirl() {
        return !this.isBoy
    }
}

The code is shorter and the computed properties are reactive to props changes.

Upvotes: 3

Lili
Lili

Reputation: 1

The way of using computed is nice.And the reason why your watch function didn't work is that maybe the prop:gender had changed before your watch code start work. So try with watch's option, immediate: true.

Upvotes: 0

Related Questions