Dynamically Switching From One HTML Element to Another in Vue
Mar 27, 2025 pm 12:01 PM Recently a friend asked me how to dynamically change one HTML element to another in a Vue template block. For example, according to certain conditions<div> Switch element to<code><p> element. The key is how to do this without relying on a series of <code>v-if
and v-else
codes. At first I didn't care much because I couldn't see a strong reason for doing so; this was not common. However, later the same day, he contacted me again and told me that he had learned how to change the element type. He excitedly pointed out that Vue has a built-in component that can be used as a dynamic element, just what he needs.
This small feature keeps the template code simple and neat. It reduces the redundant code of v-if
and v-else
, making the code easier to understand and maintain. This allows us to create well-written and more complex conditions in a script block using methods or computed properties. These things should be placed in scripts, not in template blocks.
The main reason I wrote this article is that this function is used in many places in the design system we work for. Admittedly, this is not a big feature and is hardly mentioned in the documentation, at least as far as I can tell. However, it has the potential to help render specific HTML elements in components.
Vue's built-in<component></component>
element
There are several features in Vue that can easily change views dynamically. One of the features is built-in<component></component>
element, which allows components to switch dynamically. There is a short description of using this element with an HTML element in the Vue 2 and Vue 3 documentation; this is the part we are going to explore now.
The concept is to use<component></component>
This characteristic of an element replaces commonly used HTML elements that are similar in nature but have different functions, semantics or visual effects. The following basic examples will demonstrate the potential of this element in keeping Vue components simple and neat.
Button or link?
Buttons and links are often used interchangeably, but their functions, semantics and even visuals vary greatly. Generally speaking, the button (<button></button>
) is used for internal operations in the current view and is bound to JavaScript code. On the other hand, link (<a></a>
) is intended to point to another resource, whether it is a resource on the host server or an external resource; in most cases it is a web page. Single-page applications tend to rely more on buttons than links, but both are needed.
Links are often visually designed to look like buttons, just like the buttons created by Bootstrap's .btn
class. With this in mind, we can easily create a component that switches between these two elements according to a single prop. By default, the component will be a button, but if http://ipnx.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60
prop is applied, it will render as a link.
This is in the template<component></component>
:
<component :https: :is="element"><slot></slot></component>
This binding property points to a computed property named element
, while the binding http://ipnx.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60
property uses the appropriately named http://ipnx.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60
prop. This takes advantage of Vue's normal behavior, that is, if prop has no value, the bound properties will not appear in the rendered HTML element. Whether the final element is a button or a link, slot provides internal content.
Calculating properties is simple:
element() { return this.http://ipnx.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60 ? 'a' : 'button'; }
If there is http://ipnx.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60
prop, then the application<a></a>
element; otherwise we get one<button></button>
.
<my-button> This is a button</my-button> <my-button https:> This is a link</my-button>
HTML is presented as follows:
<button>This is a button</button> <a https:>This is a link</a>
In this case one might expect the two elements to be visually similar, but they are obviously different for semantic and accessible needs. That is, the elements of the two outputs do not have to have the same style. You can use an element with the selector div.my-button
in a style block, or create a dynamic class that changes according to the element.
The overall goal is to simplify things by allowing a component to render as two different HTML elements as needed - no v-if
or v-else
!
Ordered or unordered list?
Similar to the button example above, we can create a component that outputs different list elements. Since both unordered and ordered lists use the same list item (<li>
) element as child elements, so this is easy to implement; we just need to exchange<ul></ul>
and<ol></ol>
. Even if we want to choose to use the description list<dl></dl>
, this is also easy to implement, because the content is just an acceptable one<dt></dt>
/<dd></dd>
Combined slot. The template code is very similar to the button example:
<component :is="element"><slot> No list items!</slot></component>
Please note the default content inside the slot element, which I will talk about later.
There is a prop that specifies the list type to use, defaulting to ul
:
props: { listType: { type: String, default: 'ul' } }
Similarly, there is a computed property called element
:
element() { if (this.$slots.default) { return this.listType; } else { return 'div'; } }
In this case, we are testing whether the default slot exists, which means it has content to render. If present, use the list type passed through listType
prop. Otherwise, the element will become<div> , this will display the "No list items!" message inside the slot element. This way, if there is no list item, the HTML will not render as a list with only one item declared without items. It's up to you, though, but it's nice to consider the semantics of a list without obviously valid items. Another thing to consider is that the auxiliary tools can be confused as to think that this is a list with only one project declaration without projects. Just like the button example above, you can also style each list in different styles. This can locate elements with the class name <code>ul.my-list
based on the selector. Another option is to dynamically change the class name based on the selected element.
This example follows a BEM-like class naming structure:
<component :class="`my-list ${element}`" :is="element"><slot> No list items!</slot></component>
The usage is as simple as the previous button example:
<my-list><li> list item 1</li></my-list> <my-list list-type="ol"><li>list item 1</li></my-list> <my-list list-type="dl"><dt>Item 1</dt> <dd> This is item one.</dd></my-list> <my-list></my-list>
Each instance renders the specified list element. However, the last instance will generate a Even if these two examples are essentially changing the root element component, consider going deeper into the component. For example, the title may need to be based on certain conditions from If you find yourself having to use ternary operators to control what's more than a few properties, I recommend sticking with When creating components, if there is a simple Consider everything we’ve covered so far and apply it to a flexible card component. This card component example allows three different types of cards to be placed in a specific part of the article layout: Think of these as following the design system, and components control HTML for semantics and styling. In the example above, you can see the hero card at the top, followed by a series of call to action cards, and then—scroll down a little—you will see the message card on the right. Here is the template code for the card component: There are three "component" elements in the card. Each element represents a specific element within the card, but will change according to the card type. Each component calls There may be many ways to deal with this, but you have to move in a direction that suits your component needs. In this case, there is an object that tracks the HTML element tags for each part of each card type. The method then returns the required HTML element based on the current card type and the parameters passed in. For styles, I inserted a class on the root element of the card that is based on the type of the card. This makes it very easy to create each type of CSS as required. You can also create CSS based on the HTML element itself, but I prefer classes. Future changes to card components may change the HTML structure and are unlikely to change the logic of creating the class. The card also supports background images on the title of the hero card. This is done by placing a simple computed attribute If the image URL is provided in Here is the hero card in this demo: You will see that each section of the card has its own content slot. And, for simplicity, text is the only thing expected in the slot. The card component processes the required HTML elements according to the card type. Making components expect only text makes using components quite simple. It replaces the need to make decisions about HTML structure, thus simplifying the implementation of cards. For comparison, here are two other types used in the demo: Again, note that each slot only expects text, as each card type generates its own HTML element according to the definition of Weirdly named in Vue component Here is a new technology example shared by a friend, which has become an amazingly useful tool in the Vue feature I have used. I hope this post will pass on ideas and information about this little feature to you and let you explore how to take advantage of it in your own Vue project.<ol></ol>
To show the sort order, and then switch back when finished? Now we are controlling the elements
<h1></h1>
Change to<h3></h3>
.
v-if
. Writing more code to handle properties, classes, and properties only makes the code more complex than v-if
. In these cases, v-if
will make the code simpler in the long run, while simpler code is easier to read and maintain.v-if
to switch between elements, consider this small aspect of Vue's main functionality. Extended ideas, flexible card system
<li> Hero Card: This is expected to be used at the top of the page and is more eye-catching than other cards.
<li> Call to Action Card: Used as a series of user actions before or within the article.
<li> Information card: used for excerpts.
<component :class="`card ${type}`" :is="elements('root')">
<component :style="bg()" :is="elements('header')">
<slot name="header"></slot>
</component>
<div>
<slot name="content"></slot>
</div>
<component :is="elements('footer')">
<slot name="footer"></slot>
</component>
</component>
elements()
method with a parameter that identifies which part of the call card.elements()
method is: elements(which) {
const tags = {
hero: { root: 'section', header: 'h1', footer: 'date' },
cta: { root: 'section', header: 'h2', footer: 'div' },
info: { root: 'aside', header: 'h3', footer: 'small' }
}
return tags[this.type][which];
}
bg
on the title element. Here is the computed attribute: bg() {
return this.background ? `background-image: url(${this.background})` : null;
}
background
prop, the computed property returns a string for inline styles that apply the image as the background image. A fairly simple solution that can easily make it more powerful. For example, it can support custom colors, gradients, or default colors (if no image is provided). This example does not involve a lot of possibilities, as each card type may have its own optional prop for developers to take advantage of.<custom-card background="https://picsum.photos/id/237/800/200" type="hero">
<template v-slot:header>Article Title</template>
<template v-slot:content>Lorem ipsum...</template>
<template v-slot:footer>January 1, 2011</template>
</custom-card>
<custom-card type="cta">
<template v-slot:header>CTA Title One</template>
<template v-slot:content>Lorem ipsum dolor sit amet, consistetur apiscing elit.</template>
<template v-slot:footer>footer</template>
</custom-card>
<custom-card type="info">
<template v-slot:header>Here's a Quote</template>
<template v-slot:content>“Maecenas ... quis.”</template>
<template v-slot:footer>who said it</template>
</custom-card>
elements()
method. If you think in the future that different HTML elements should be used, you just need to update the component. Building accessibility features is another potential future update. Interaction functionality can even be expanded based on card type. The power of components in components
<component></component>
Elements were originally designed for one thing, but as often happens, it has a small side effect that makes it very useful in other ways.<component></component>
Elements are designed to dynamically switch Vue components within another component as needed. A basic idea about this might be a tab system for switching between components that act as pages; this is actually explained in the Vue documentation. But it supports doing the same for HTML elements.
The above is the detailed content of Dynamically Switching From One HTML Element to Another in Vue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
