Table of Contents
Vue's built-in element
Button or link?
Ordered or unordered list?
Now we are controlling the elements
Extended ideas, flexible card system
The power of components in components
Home Web Front-end CSS Tutorial Dynamically Switching From One HTML Element to Another in Vue

Dynamically Switching From One HTML Element to Another in Vue

Mar 27, 2025 pm 12:01 PM

Dynamically Switching From One HTML Element to Another in Vue

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.

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 https://www.php.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>
Copy after login

This binding property points to a computed property named element , while the binding https://www.php.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60 property uses the appropriately named https://www.php.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.https://www.php.cn/link/ed2ddd0dcd323046d0f9a51e5cc51c60 ? 'a' : 'button';
}
Copy after login

If there is https://www.php.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>
Copy after login

HTML is presented as follows:

 <button>This is a button</button>
<a https:>This is a link</a>
Copy after login

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>
Copy after login

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'
  }
}
Copy after login

Similarly, there is a computed property called element :

 element() {
  if (this.$slots.default) {
    return this.listType;
  } else {
    return 'div';
  }
}
Copy after login

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>
Copy after login

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>
Copy after login

Each instance renders the specified list element. However, the last instance will generate a

, declare that there is no list item, because, well, there is no list to be displayed! One might wonder why you want to create a component that switches between different list types when it can be just simple HTML. While there may be many benefits to include a list in a component for styling and maintainability reasons, other reasons can be considered. For example, what if some form of functionality is bound to a different list type? Maybe consider sorting the list and switching to<ol></ol> To show the sort order, and then switch back when finished?

Now we are controlling the elements

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<h1></h1> Change to<h3></h3> .


If you find yourself having to use ternary operators to control what's more than a few properties, I recommend sticking with 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.

When creating components, if there is a simple v-if to switch between elements, consider this small aspect of Vue's main functionality.

Extended ideas, flexible card system

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:

    <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.

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:

<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>
Copy after login

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 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];
}
Copy after login

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 bg on the title element. Here is the computed attribute:

 bg() {
  return this.background ? `background-image: url(${this.background})` : null;
}
Copy after login

If the image URL is provided in 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.

Here is the hero card in this demo:

<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>
Copy after login

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:

<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>
Copy after login

Again, note that each slot only expects text, as each card type generates its own HTML element according to the definition of 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

Weirdly named in Vue component<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.

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.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

Programming Sass to Create Accessible Color Combinations Programming Sass to Create Accessible Color Combinations Apr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

See all articles