Home > Software design >  how can I add innerhtml(or innertext) using h() function?
how can I add innerhtml(or innertext) using h() function?

Time:05-25

For some reasons I need to use virtual DOM and Here is my code,

// test.js
import { h, ref } from 'vue'

const ButtonCounter = {
  name: 'button-counter',
  props: {
    tag: {
      type: String,
      default: 'div'
    }
  },
  setup (props) {
    const sliderClass = ref('slider-slide')
    return () => {
      return h(props.tag, {
        class: sliderClass.value
      })
    }
  }
}

export { ButtonCounter }
<template>
  <div>
    <div id="components-demo">
      <!-- putting <img>tag in virtual DOM -->
      <button-counter tag="span"><img src="../assets/images/red.jpg" alt=""></button-counter>
    </div>
  </div>
</template>
<script>
import { ButtonCounter } from '../assets/js/test'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'

export default {
  name: 'TestView',
  components: {
    ButtonCounter,
    Swiper,
    SwiperSlide
  },
  setup () {
  }
}
</script>

I expected <img src="../assets/images/red.jpg" alt=""> to be added in <span ></span> but the result was, https://i.stack.imgur.com/DR4Te.png it wasn't added.

How can I make it work? Thank you for your help.

CodePudding user response:

The h render function doesn't automatically just render the scope (i.e. the inner/wrapped part of the component) without you explicitly telling it to.

This snippet should do it:

setup (props, { slots }) {
  const sliderClass = ref('slider-slide');
  return () => {
    return h(props.tag, {
      class: sliderClass.value
    }, slots.default());
  };
}

Note the addition of the call to slots.default(), added as the children parameter for the render function.

  • Related