Search code examples
vue.jsvuejs2slotcomputed-properties

Can I use computed properties within component's slot?


Recently I found out that I can't use computed property or a data properties within the components slot. Even though computed is defined in the component, I am not able to use it in the component's slot. Is there any way of getting it work?

Example code:

Vue.component('test-component', {
   template: '<div><slot></slot></div>',
   computed: {
      my_computed: function(){
         return 2+3; // not defined in slot
      }
    }
})
<div id="app">
     <test-component>
        <span v-text="my_computed"></span>
     </test-component>
</div>

See live example here, https://jsfiddle.net/gu9jh4n0/1/


Solution

  • You could use a Scoped Slot to achieve that.

    In your example, your component will look like this :

    Vue.component('test-component', {
      template: '<div><slot :computed="my_computed"></slot></div>',
      computed: {
        my_computed: function(){
            return 2+3; // not defined in slot
        }
      }
    });
    

    And the main template will retrieve the slot's scope and use the computed :

    <test-component>
      <span slot-scope="data" v-text="data.computed"></span>
    </test-component>
    

    Live example.