Vue: Slots cannot be toggled using v-if directive

Created on 27 Apr 2017  路  5Comments  路  Source: vuejs/vue

Version

2.3.0

Reproduction link

https://jsfiddle.net/teddyrised/nkomyf9g/

Steps to reproduce

  1. Set up app so that we have a built-in toggle, say showSlot, stored in the data object of the app
  2. The app contains components, in which contain slots
  3. In the component template, define slots so that one can be toggled using v-if based on the showSlot value
  4. Go to console. Type in app.showSlot = true

Markup:

<div id="root">
  <custom desc="Slot that is always shown"><template slot="test-slot">{{ this.content }}</template></custom>
  <custom desc="Slot that is conditionally shown"><template v-if="this.showSlot" slot="test-slot">{{ this.content }}</template></custom>
</div>

JS:

Vue.component('Custom', {
  template: '#template',
  props: {
    desc: String
  },
  computed: {
    hasSlotData() {
        return this.$slots['test-slot'];
      }
  }
});

var app = new Vue({
  el: '#root',
  data: {
    content: 'foobar',
    showSlot: true
  }
});

What is expected?

The <template v-if="this.showSlot" slot="..."> should be rendered when app.showSlot is set to true.

What is actually happening?

The <template v-if="this.showSlot" slot="..."> remains unrendered.


I was creating an app where the slot should be conditional, so that it is not rendered when not necessary.

Most helpful comment

Never use this in the template:

<template v-if="showSlot"

not

<template v-if="this.showSlot">

second mistake, use

`v-if="$slots['test-slot']"

instead of computed property because $slots are not reactive

FIxed jsfiddle: https://jsfiddle.net/q4kmyqdh/

All 5 comments

Never use this in the template:

<template v-if="showSlot"

not

<template v-if="this.showSlot">

second mistake, use

`v-if="$slots['test-slot']"

instead of computed property because $slots are not reactive

FIxed jsfiddle: https://jsfiddle.net/q4kmyqdh/

@sqal Thanks for the quick response :+1. I didn't know that this.$slots are not reactive. Is it not possible to encapsulate that logic in a method, instead of writing it in the markup?

@terrymun Sure, you can move the logic to the method, it will work because method will be called on every re-render

@sqal Thanks again! You really opened my eyes on how computed properties and methods can be so different. And I didn't know you can use methods like that--I've always thought they are meant to be triggered by user interaction :)

Similar to #3517

Was this page helpful?
0 / 5 - 0 ratings

Related issues

paceband picture paceband  路  3Comments

franciscolourenco picture franciscolourenco  路  3Comments

loki0609 picture loki0609  路  3Comments

robertleeplummerjr picture robertleeplummerjr  路  3Comments

wufeng87 picture wufeng87  路  3Comments