Wenfang Du
Wenfang Du

Reputation: 11347

How to use <Comment> component in JSX?

The following <Comment>Foo</Comment> produces <!--[object Object]--> comment node in the DOM tree.

How to use it so that it can produce <!--Foo-->?

<script>
  import { Comment } from 'vue'

  export default {
    render() {        👇
      return <Comment>Foo</Comment>
    },
  }
</script>

Upvotes: 1

Views: 83

Answers (1)

tony19
tony19

Reputation: 138336

You'd have to create a wrapper component to insert text as a child of Comment. The following MyComment functional component flattens the text nodes from its default slot, and passes the result as the Comment child:

// @/components/MyComment.js
import { Comment, h } from 'vue'

const getText = node => {
  if (typeof node === 'string') return node
  if (Array.isArray(node)) {
    return node.map(getText).join('')
  }
  if (node.children) {
    return getText(node.children)
  }
}

export const MyComment = (props, {slots}) => h(Comment, slots.default && getText(slots.default()))

Then use it in your JSX:

import { MyComment } from '@/components/MyComment'

export default {
  render() {
    return <div>
      <span>foo bar</span>
      <MyComment>This is a comment</MyComment>
    </div>
  }
}

Upvotes: 1

Related Questions