A guide to leveraging Vue's Dynamic Component with a Fragment

Is it feasible to utilize Vue's <component> element to selectively display a component or nothing at all?

Let's consider the following scenario:

<component :is="hasTooltip ? 'CustomTooltip' : 'div'">
  <div>Hover over me!</div>
</component>

In this example, we are showing a CustomTooltip component when the value of hasTooltip is true, otherwise we are displaying a regular div. Is there a way to display a fragment instead of this div (similar to React's <> fragment) that will be removed in the browser? How can this be achieved? I am using Vue 2.0.

Simply rendering the component based on conditions will not suffice as we still want the "Hover over me!" text to appear.

Answer №1

Could a solution similar to this work?

Vue.component('tooltip', {
  template: `<div> Tooltip for: <slot></slot> </div>`
})

Vue.component('wrap-if', {
  functional: true,
  props: ['wrap', 'wrapper'],
  render(h, ctx) {
    
    if (ctx.props.wrap) {
      return h(ctx.props.wrapper, ctx.data, ctx.children)
    } else {
      // Potentially verifying that children.length === 1 since Vue 2 doesn't support fragments
      return ctx.children
    }
  }
})

new Vue({
  el: '#app',
  data: {
    wrap: true
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f292a3a1f6d7169716e6b">[email protected]</a>/dist/vue.js"></script>

<div id="app">
  <wrap-if :wrap="wrap" wrapper="tooltip">
      <span>This is always rendered no matter what</span>
  </wrap-if>
  <br>
  <button @click="wrap = !wrap">Toggle</button>
  <pre>{{$data}}</pre>
</div>

Answer №2

Combining various insights from different comments, I have compiled them into a cohesive answer.

It seems like there is no straightforward way to conditionally wrap a component in Vue-2 without using a plugin, due to the absence of fragments.

Nevertheless, this issue can be resolved by either utilizing a Vue-2 fragment plugin or, in Vue3, employing the fragment component. For more information, refer to this response. Instead of displaying the div, display the fragment.

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

Filtering data in Angular based on specific dates

Upon receiving data from an Angular service, I have a JSON object structured like this: [ { "id": 2, "order_status": "R", "order_date": "2015-09-12T07:58:24.733834Z", "update_timestamp": "2015-10-05T04:22:44.904227Z" ...

Unable to establish a connection with the node at http://localhost:8545

Issues Encountered: I am having trouble with the Web3.min.js path in my system directory! The Web3.min.js file is being loaded from a folder in my browser. I have copied the web3.min.js file to the same folder where the index.html file is l ...

How can I stop Jquery Mobile from processing the URL hash?

Currently implementing Jquery Mobile in a preexisting web application is posing a challenge. The issue arises as Jquery Mobile is interpreting all URL hashes by default. For example: mysite.com/#foo In this case, the hash 'foo' is being directe ...

Comparing Ajax methods: Which one reigns supreme?

I am seeking advice on the best approach to handle a series of Ajax insert, update, and delete operations. Which method is more effective? Creating individual methods for each function (e.g., delete_foo, insert_foo, update_foo, delete_bar, insert_bar, ...

Ensure that all the checkboxes in a specific column are selected for every row within the gridview

I recently created a gridview with various columns, some of which are hidden boundfields and others that contain dynamically created templated fields with checkboxes. The number of checkbox columns varies depending on the query. Each checkbox in the heade ...

New ways to update Vue.js data without the need to bind HTML to methods

In my Vue.js application, I have a file where users can choose from different graphs by setting the activeOrderView variable through a @click event. Each graph has its own set of x-axis categories and y-axis values. The issue I am facing is that when a us ...

Creating Customizable Badges That Can Be Embedded in Laravel

I am looking to implement organic promotion in my application using Laravel by providing badges, which are snippets of content that users can embed on their own websites when a URL is stored in our database. These badges could be similar to the DMCA embed ...

Transmitting a JSON string to my backend system to insert into my database, but unfortunately, no data is being added

I've been facing a challenging issue with my code Currently, I am attempting to insert an object into my database using jQuery/AJAX. Despite not encountering any errors, the data is not getting added to my DB. Here is the snippet of my JS/JQuery cod ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

Implementing Vue Js checkboxes using dynamic JSON data

I have a product search page where users can filter based on selected category. When a category is chosen, the API returns the following response: "customFields":{ "select":{ "brand":{"options":[ "nike", "adidas","puma"]}, "colour" ...

Embedding Google+ Sharing in an iframe

I'm currently working on a web application that needs to be compatible with PC, tablets, and mobile phones. I'm interested in integrating Google+ Sharing into the app. However, it appears that when using the url , there are issues with blocking ...

I am looking to determine the number of instances where the element 500 appears in each column (1-4) of an HTML table using jQuery or JavaScript. What would be the best approach to achieve this goal?

Does anyone know a way to use either jQuery or JavaScript to count how many times the number 500 appears in each column (1-4) of an HTML table? Any suggestions on how I can achieve this? <html> <table> <thead> <tr> &l ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

How to select child elements of the <video> tag using jQuery

I'm currently in the process of updating the src attributes for the <source> elements within my <video> container. Initial Markup <video id='myVidID' class='video-js vjs-default-skin' controls autoplay preload=&apo ...

Observing the Result of a Function within a Controller Using Ng-Repeat in a Directive

I'm struggling with making a custom directive watch the result of a function that's bound to the scope in the controller. Here is the HTML. I'm passing the key of the ng-repeat to the function in the controller in order to determine whether ...

Incorporating modules through System.JS

I integrated angular2-google-maps into my Angular 2 application for utilizing Google Maps functionality. Here is a snippet from my package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurre ...

Input Error in ASP.NET JavaScript

Within my ASP.NET website, I have implemented an <asp:TextBox /> where the text input is encoded using HttpUtility.HtmlEncode(); Furthermore, the page is equipped with validation controls like <asp:RequiredFieldValidator /> and <asp:CustomV ...

Steps to resolve the Firebase alert stating "you're currently utilizing the development version of Firebase"

Despite following the standard advice I found on various sources to fix this warning in my Vue app, it still persists. This is how I am importing Firebase: import firebase from 'firebase/app'; import 'firebase/app'; import 'fireba ...

Make sure the division remains fixed even when the window is resized

Having a fixed position and bottom set to 0, I want my div to display at the bottom of the window. The issue arises when the window is resized, causing the div to move up and into other elements. For instance, when opening the console box in Chrome, the f ...

Vue-CLI-Service CPU Performance

Having an issue with my dockerized vue-cli app running on NGINX environment. Every time the container starts, CPU usage spikes to almost 100%, then drops, and repeats this pattern. The culprit seems to be "/app/node_modules/.bin/vue-cli-service". This i ...