Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I add innerhtml(or innertext) using h() function?

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 class="slider-slide"></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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading