Only show slot if it has content

后端 未结 6 1383
感情败类
感情败类 2021-01-30 20:00

Is there a way to only display a slot if it has any content?

For example, I\'m building a simple Card.vue component, and I only want the footer displayed if

6条回答
  •  轮回少年
    2021-01-30 20:08

    Initially I thought https://stackoverflow.com/a/50096300/752916 was working, but I had to expand on it a bit since $scopeSlots returns a function which is always truthy regardless of its return value. This is my solution, though I've come to the conclusion that the real answer to this question is "doing this is an antipattern and you should avoid it if possible". E.g. just make a separate footer component that could be slotted in.

    Hacky solution

       hasFooterSlot() {
            const ss = this.$scopedSlots;
            const footerNodes = ss && ss.footer && ss.footer();
            return footerNodes && footerNodes.length;
       }
    

    Best Practice (helper component for footer)

    const panelComponent = {
      template: `
        
    ` } const footerComponent = { template: ` ` } var app = new Vue({ el: '#app', components: { panelComponent, footerComponent }, data() { return { name: 'Vue' } } })
    .nice-panel {
      max-width: 200px;
      border: 1px solid lightgray;
    }
    
    .nice-panel-content {
      padding: 30px;
    }
    
    .nice-panel-footer {
      background-color: lightgray;
      padding: 5px 30px;
      text-align: center;
    }
    
    

    Panel with footer

    lorem ipsum

    Panel without footer

    lorem ipsum

提交回复
热议问题