How to create a non-empty comment node using `h`?

1k views Asked by At

The following code will produce an empty comment node i.e. <!---->.
How to produce a non-empty comment node e.g. <!-- Foo --> using h?

export default {
  render(h) {
    return h(null)
  },
}
1

There are 1 answers

1
tony19 On BEST ANSWER

It seems Vue 2.6.14 no longer allows doing any of the following, but it's possible in Vue 3.

Option 1: h(null) with string as second argument

import { h } from 'vue' //  Vue 3

export default {
  render() {
    return h(null, 'This is a comment')  // <!--This is a comment-->
  },
}

Note: This generates a runtime warning about using null:

[Vue warn]: Invalid vnode type when creating vnode: null

You could workaround that with resolveDynamicComponent(null) instead of null:

import { h, resolveDynamicComponent } from 'vue' // Vue 3

export default {
  render() {
    return h(resolveDynamicComponent(null), 'This is a comment')  // <!--This is a comment-->
  },
}

Option 2: h(Comment) with string as second argument

import { h, Comment } from 'vue' // Vue 3

export default {
  render() {
    return h(Comment, 'This is a comment')  // <!--This is a comment-->
  },
}

Option 3: createCommentVNode() with string as argument

import { createCommentVNode } from 'vue' // Vue 3

export default {
  render() {
    return createCommentVNode('This is a comment')  // <!--This is a comment-->
  },
}

Note: createCommentVNode is an internal API, which can be removed/renamed in a future release, so use it with caution.

Vue 3 demo