Skip to content
Advertisement

Check if props in vue.js component template exists

After tried many variations, I don’t know how to properly style a component’s slot or partial code within <template></template> section.

Is there a way to check if props <counter :recent="true"></counter> from parent level exists, so in a Counter.vue in section <template></template> i would show a special html markup for it ?

=== UPDATED ===

Vue.component('counter', {
	template: `
<span class="counter" :number="21" v-text="number">
	<span v-if="recent">
  	since VARTIME
  </span>
</span>
  `,
  data: function(){
  	return{
    	count: this.number + 1
    }
  },
  props: {
  	number: Number,
    recent: {
    	type: Boolean,
      default: false
    }
  },
  computed: {
  	
  },
  created(){
  	if( this.recent === true ){
    	console.log('mounted recent true');
    }
  }
});

new Vue({
	el: "#app",
  
  data: {
  	count: ''
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">

  <counter :number="20" :recent="true"></counter>
  
</div>

Advertisement

Answer

Here the default value for the recent will be false and if the recent is passed from the parent it will get set in the child.

Just use the detailed props definition as mentioned here.

Remove the v-text="number" as it overrides the internal content of the span and therefore the v-if will never executes.

This is a working example

Vue.component('counter', {
  template: `
    <span class="counter" :number="21">
      <span v-if="recent"> since VARTIME </span>
    </span>
  `,
  data: function() {
    return {
        count: this.number + 1    
    }
  },
  props: {
    number: Number,
    recent: {
      type: Boolean,
      default: false
    }
  },
  computed: {},
  created() {
    if ( this.recent === true ) {
        console.log('mounted recent true');
    }
  }
});

new Vue({
  el: "#app",
  data: {
    count: ''
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">

  <counter :number="20" :recent="true"></counter>
  
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement