1

As answered here, we can check if a slot has content or not. But I am using a slot which has no name:

<template>
    <div id="map" v-if="!isValueNull">
        <div id="map-key">{{ name }}</div>
        <div id="map-value">
            <slot></slot>
        </div>
    </div>
</template>

<script>
    export default {
        props: {
            name: {type: String, default: null}
        },
        computed: {
            isValueNull() {
                console.log(this.$slots)
                return false;
            }
        }
    }
</script>

I am using like this:

<my-map name="someName">{{someValue}}</my-map>

How can I not show the component when it has no value?

Akshdeep Singh
  • 1,301
  • 1
  • 19
  • 34

2 Answers2

3

All slots have a name. If you don't give it a name explicitly then it'll be called default.

So you can check for $slots.default.

A word of caution though. $slots is not reactive, so when it changes it won't invalidate any computed properties that use it. However, it will trigger a re-rendering of the component, so if you use it directly in the template or via a method it should work fine.

Here's an example to illustrate that the caching of computed properties is not invalidated when the slot's contents change.

const child = {
  template: `
    <div>
      <div>computedHasSlotContent: {{ computedHasSlotContent }}</div>
      <div>methodHasSlotContent: {{ methodHasSlotContent() }}</div>
      <slot></slot>
    </div>
  `,
  
  computed: {
    computedHasSlotContent () {
      return !!this.$slots.default
    }
  },
  
  methods: {
    methodHasSlotContent () {
      return !!this.$slots.default
    }
  }
}

new Vue({
  components: {
    child
  },
  
  el: '#app',
  
  data () {
    return {
      show: true
    }
  }
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>

<div id="app">
  <button @click="show = !show">Toggle</button>
  <child>
    <p v-if="show">Child text</p>
  </child>
</div>
skirtle
  • 27,868
  • 4
  • 42
  • 57
0

Why you dont pass that value as prop to map component.

<my-map :someValue="someValue" name="someName">{{someValue}}</my-map>

and in my-map add prop:

   props: {
            someValue:{default: null},
        },

So now you just check if someValue is null:

 <div id="map" v-if="!someValue">
    ...
</div
N. Djokic
  • 898
  • 1
  • 6
  • 19