Search code examples
javascriptvue.jsvuejs2vuejs3vue-render-function

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


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)
  },
}

Solution

  • 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