How to use Vue.js in a blog post

March 29, 2020 2 minutes reading time Development vue

When I watched the video “Extracting Reusable Components” by Adam Wathan, the creator of Tailwind CSS and Tailwind UI, I wondered how to embed Tailwind CSS styled cards with dynamic content within a blog post.

Use Vue.js

Since Vue.js generates the cards dynamically from an array of data, the page needs to load it. Not every page needs Vue.js, so it’s best to turn it on only for those pages that really need it. I decided to control it via a switch in the posts frontmatter:

---
vue: true
---

Modify Hugo head template

We need to evaluate the switch for enabling Vue.js and load the JavaScript only if enabled. For my own template the right place is layouts/partials/head.html:

{{ if .Params.Vue }}
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
{{ end }}

The result

Here is how it looks within a post in this Hugo-powered blog:

Popular destinations
A selection of great work-friendly cities with lots to see and explore.
{{ destination.name }}
${{ destination.avg }} / night average
Explore {{ destination.props }} properties
{{ destination.reviews }} reviews
{{ quote }} - Kanye West

I have created this GitHub Gist with all the necessary code in case you want to look it up.