简体   繁体   中英

How to get the default content slot sent to a Vue component?

In the following example, I would like a component that doubles a number. This number is passed not as a property, but as content. How is it possible to get the content value in Vue?

 var twice = { template: '<div>{{ value }}</div>', computed: { value() { return parseInt(this.$slot) * 2; } } }; new Vue({ el: '#app', components: { twice: twice } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script> <div id="app"> <twice>21</twice> </div>

You could access the default slot text by this.$slots.default[0].text :

 var twice = { template: `<div> number : <slot></slot><br> <div>double : {{ value }}</div> </div>`, computed: { value() { return parseInt(this.$slots.default[0].text) * 2; } }, mounted() { console.log(this.$slots.default[0].text) } }; new Vue({ el: '#app', components: { twice: twice } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <twice>21</twice> <div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM