简体   繁体   中英

Render one of child in vue template

How can I render one of $children in current vue template?

For example, I have a 3 $children, is it possible to render this.$children[1] ?

this.$children[1] is looks like:

在此处输入图像描述

You can use render function to achieve that. Imagine you have a Parent component, for which you want to always render just the first child. You use this component like this:

<Parent>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, maiores.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, maiores.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, maiores.</p>
</Parent>

And this is how your parent component would look like:

<script>
  export default {
    render(createElement) {
      return createElement('div', [this.$slots.default[0]])
    }
  }
</script>

This is just to demonstrate the approach - this specific code will fail if you don't have any children - so you need to add a check for that in your render function.

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