Vue.js Cheat Sheet

Vue.js cheat sheet: Rendering data into HTML

By Ondrej PolesnyMay 3, 2021

Are you just starting out with Vue.js? Or has it been long since you’ve worked with Vue? This cheat sheet lists the nine most common tasks and solutions when outputting data to HTML.

In all these samples, the first part shows the syntax, and the second part shows the usage with real data.

Outputting data into HTML

The first test of your app or rendering data between HTML elements:

{{ variable }}
{{ metadata.subtitle.value }}
 

Adding the standard class attribute

After testing the app, you want to make it look nice with styles:

<... class="classname">
<div class="sidebar__inner">

Outputting data into HTML attributes

When adding links or rendering images with alt tags, this is how you can fill the elements’ attributes:

< ... :name="variable">
<a :href="`https://twitter.com/${author.twitter.value}`">

Outputting HTML

In certain cases, like when consuming rich texts from a headless CMS, you need to render already formatted HTML:

< ... v-html="variable"></...>
<div v-html="article.teaser"></div>

Iterating over data sets

Iterating is useful for creating lists of items, like index pages of blogs or product catalogs:

< ... v-for="item in collectionVariable" :key="item.uniqueKey">
<article v-for="article in articles" :key="article.id" ... >

Iterating over data sets with index

The same use case as before, but this way, you can access an index of each item:

< ... v-for="(item, index) in collectionVariable" :key="item.id">
<article v-for="(article, index) in articles" :key="article.id" ... >


Rendering conditional markup

Conditions allow you to hide or display specific parts of markup based on data:

<... v-if="variable !== null">
<div v-if="data.length > 0"> ... </div>

Rendering conditional markup including else branch

They can also be used to display preloaders in case of async data fetching to let your visitors know that something is happening:

<... v-if="variable !== null"> ...
<... v-else>
<div v-if="data.length > 0"> ... </div>
<div v-else>Loading...</div>

Passing data to child components

When you start using components, this is how you can provide them with data from the parent:

<component :componentVariable="variable">
<links :author="author">

You can also download this cheat sheet in printable form and check out its alternatives for React and Angular.

Written by
Ondrej Polesny

As Developer Evangelist, I specialize in the impossible. When something is too complicated, requires too much effort, or is just simply not possible, just give me a few days and we will see :).

More articles from Ondrej

Subscribe to Kentico Kontent Newsletter

Stay in the loop. Get the hottest updates while they’re fresh!