iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐕

Change Head Elements in Vue3 | Vue3 (Options API) + Unhead

に公開

Overview

When building a multi-page SPA with Vue and Vue Router, I wanted to change the title (the site name displayed in the browser tab) for each page. That's when I found that using a module called Unhead makes this possible.

Notes

  • Unhead has V1 and V2: V1 is for Vue2, V2 is for Vue3
  • Unhead V2 is designed for Vue3's Composition API
  • This time, I'll implement it with Vue3's Options API

Installation

Directory Structure

src/
├ views/
│   └ HomeView.vue
└ main.js

Code

npm i @unhead/vue
main.js
import { VueHeadMixin, createHead } from '@unhead/vue/client';
                                      //  ^^^^^^^^^^^^^^^^^^^^^^  Note!
const app = createApp(App);
const head = createHead(); 
app.use(head);
app.mixin(VueHeadMixin);
app.mount('#app');
HomeView.vue
<script>
export default {
  name: "HomeView",
  head() {
    return {
      title: 'Page Title',
      meta: [
        { 
          name: 'description',
          content: 'Site description' ,
        },
        {
          property: 'og:title',
          content: 'OGP Title',
        },
        {
          property: 'og:description',
          content: 'OGP Description',
        }
      ],
    };
  },
};
</script>

Discussion