Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 360
El Danielo Avatar asked Jan 26 '18 10:01

El Danielo


People also ask

Can we use computed property in V model?

The combination of the v-model and computed property makes your code robust and more reusable. Hope this article helps you to understand how to use two-way data binding in Vue. js by using the v-model directive and computed properties.

What is the difference between a computed property and methods in VUE JS?

A computed property is cached, which implies that, for accessing data, the function runs just once if the value remains unchanged. Methods, on the other hand, need to run data properties checks every time, because they cannot tell otherwise if the values are changed inside the method property.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

What is the difference between watchers and computed property in Vuejs?

Computed properties are used to calculate the value of a property based on some other conditions. Watchers, on the other hand, are not primarily used for changing the value of a property; instead, they are used to notify you when the value has changed and let you perform certain actions based on these changes.


1 Answers

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.

like image 163
Thomas Ferro Avatar answered Sep 17 '22 22:09

Thomas Ferro