Can I use computed properties within component's slot?
Asked Answered
S

1

6

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/

Smegma answered 26/1, 2018 at 10:58 Comment(0)
G
7

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.

Gorcock answered 26/1, 2018 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.