A
A
Alexander2020-09-21 00:32:04
Vue.js
Alexander, 2020-09-21 00:32:04

How not to render a slot until it is needed?

Imagine that in some component, another component is called that uses the slot from the first one, in an area that is not always displayed.
But the problem is that in this case, the slot is still rendered in the first component, although it will not be displayed.

For understanding, I made a very simple component:

<script type="text/x-template" id="foldet-block">
  <div>
    <span class="btn-link" v-on:click="toggle">{{anchor_text}}</span>
    <div v-if="state.show"><slot></slot></div>
  </div>
</script>
<script>
  Vue.component('foldet-block', {
    props: {
      show: {type: Boolean, default: false},
      anchor: {type: String},
      anchor_show: {type: String, default: ''},
    },
    data () {
      return {
        state: {
          show: false
        },
      }
    },
    created () {
      this.state.show = this.show
      
    },
    computed: {
      anchor_text () {
        return this.state.show?this.anchor:(this.anchor_show?this.anchor_show:this.anchor)
      }
    },
    methods: {
      toggle () {
        this.state.show = !this.state.show;	
      }
    },
    template: '#foldet-block'
  });
</script>


As you can see, it simply shows or does not show the block passed to it.
Imagine that it is called inside another component:

<foldet-block
  v-bind:anchor="'показать'"
v-bind:anchor_show="'скрыть'"
  ><p>{{text}}</p></foldet-block>

And inside this component, the text variable is somehow complex. How would it not be calculated if the block in foldet-block is hidden?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-09-21
Madzhugin @Suntechnic

<foldet-block
  v-bind:anchor="'показать'"
v-bind:anchor_show="'скрыть'"
  ><template v-slot><p>{{text}}</p></template></foldet-block>

The essence of the trick is that v-slot turns the slot into scoped, and the scoped slot waits for input data from the parent to render.
PS If only one component goes to the slot (and this is a component, not a native tag), you can omit the template and put v-slot directly on the component itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question