An effective way to utilize the h() function in Vuejs to render a component instance

I'm currently working on a Vuejs component setup that resembles the following structure:

<template>
  <button @click="generateItem()">Add item</button>
  <div class="container"></div>
</template>

<script setup>
  import { h } from 'vue'
  import MyItem from '@/components/MyItem.vue'

  function generateItem(){
    return h(MyItem)
  }
</script>

My goal is to utilize the h() function to render an instance of MyItem within the div.container when executing the generateItem() function. However, despite referencing the official Vuejs documentation on the h() function, I'm unsure of how to achieve this. Any insights or suggestions on how I can accomplish this task?

Answer №1

Implement the use of v-for based on your requirements:

Custom Playground

<template>
  <button @click="generateItem()">Add item</button>
  <div class="container">
    <my-item v-for="item in items">{{ item }}</my-item>
  </div>
</template>

<script setup>
  import { reactive } from 'vue'
  import MyItem from './MyItem.vue'
  const items = reactive([]);
  let counter = 1;
  function generateItem(){
    items.push('Item ' + counter++)
  }
</script>

Answer №2

It is my understanding that the render function should not be used in conjunction with <script setup>. Instead, it serves as a flexible option for programmatically declaring your render function, rather than utilizing a template within a Vue SFC.

That being said, you can render a dynamically generated item like this:

<script setup>
  import { h, ref, shallowRef } from 'vue'
  import MyItem from './MyItem.vue'

  const component = shallowRef(null)
  function generateItem(){
    component.value = MyItem
  }
</script>

<template>
  <button @click="generateItem()">Add item</button>
  <div class="container">
    <component v-if="component" :is="component" :testStr="'The test str from App.vue'"></component>
  </div>
</template>

(you can view this in action on the playground url: Vue SFC Playground)

You can also achieve the same result by wrapping it with h(), though I consider it to be unnecessary:

component.value = h(MyItem)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the issue of PHP not receiving this multidimensional array through Ajax?

Having an issue with receiving a multidimensional array in PHP after posting it from JS using Ajax: $.ajax({ type: 'post', url: 'external_submit.php', dataType: "json", data: { edit_rfid_changes_submit ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Troubleshooting alignment problems with a responsive gallery (Bootstrap-gallery & justifyGallery)

Looking to showcase a gallery of images using jquery-justifyGallery and bootstrap-gallery. Want to display 4 images in a row, but running into issues when trying to display 5 images where the last image in the row ends up with a larger width. Bootstrap has ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

mongodb cannot locate the schema method within the nested container

Trying to access a method of a schema stored inside a mixed container has presented a challenge. The scenario is as follows: var CaseSchema = mongoose.Schema({ caseContent : {}, object : {type:String, default : "null"}, collision : {type : Boo ...

I am facing difficulties with invoking the popOpen() function within my parameters in JS, HTML, and CSS

I'm currently facing an issue with my code. I am attempting to invoke my openPop() function with the input parameter 'pop' within some of my sensor code, but no pop-up is appearing even though I believe I am calling the popup correctly. If a ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Tips on extracting the image URL from a canvas element using Selenium in Java and leveraging JavascriptExecutor

My main objective is to extract the image URL from a canvas container. Here is what I have attempted: JavascriptExecutor jse = (JavascriptExecutor) driver; Object imageURL = jse.executeScript("arguments[0].toDataURL('image/png');", canvas); Un ...

Repetitive use of multiple submit buttons in AngularJS

i'm currently working with AngularJS Currently facing this issue: view screenshot I have utilized the following HTML code to display submit button for two different types of forms. One for TEXT Form and one for ENUM Form: <div ng-controller="g ...

Setting the UrlAction in an Asp.Net Core Controller: A step-by-step guide

There is an input box for searching on the website... The following HTML code snippet shows how the search functionality is implemented: <form id="searchForm" asp-controller="Product" asp-action="SearchProduct" method=&quo ...

Debugging a script designed to output a value of 1 if the Mean equals the Mode, and 0 if they are not equal

As a beginner coder, I am working on a code that should return 1 if the mean is equal to the mode and 0 otherwise. However, my current code only outputs 0 even when it should be returning 1. Any guidance or assistance in identifying where I may have made ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

The pagination feature in vue router is malfunctioning and not functioning as intended

I have successfully implemented a query parameter for changing pages: getProducts(){ this.$router .push({ name: 'products', query: { page: this.page, }, }) .catch(() => {}) ...

What is the best way to invoke a function within a controller from a .factory service?

I have been working on a code snippet where I am trying to create a generic function. This function, when given the name of a function in my controller, should be run from a factory. app.factory('myfactory', function () { return { cre ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

Looking for an image that spans the entire height of the container

I need help with positioning an img inside a div container that has a background color. I want the image to overlay on top of the div, extending beyond its height without causing any scroll bars. Here is a fiddle related to this issue: http://jsfiddle.net ...

Using NodeJS Script in conjunction with Express and setInterval

Feeling stuck and unable to find clear answers for the best solution. I have a Node.js app that serves APIs with MongoDB as the database. I created a setInterval within the request to update the data every 30 seconds. This was done to prevent the Node.js ...

Difficulty understanding JavaScript sum calculations

I am currently working on a website project. Seeking assistance to enable an increment of one when clicked. Also need guidance on calculating the total price of items collected in a designated section under "number of items selected". Goal is to display ...

What are some ways to personalize a scrollbar?

I am looking to customize the scrollbar within a div. I attempted to modify it using the code below, but I encountered difficulties when trying to change the scroll buttons and did not achieve my desired outcome. Additionally, this customization did not wo ...