2.3.0
https://jsfiddle.net/teddyrised/nkomyf9g/
showSlot, stored in the data object of the appv-if based on the showSlot valueapp.showSlot = trueMarkup:
<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
}
});
The <template v-if="this.showSlot" slot="..."> should be rendered when app.showSlot is set to true.
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.
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
Most helpful comment
Never use
thisin 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/