Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData().

According to the Nuxt.js documentation, asyncData() is triggered before loading page components and combines with component data.

However, I keep receiving this error message:

The property 'title' does not exist on type '{ asyncData({ app, params }: Context): Promise<{ title: string | undefined; excerpt: string | undefined; feature_image: Nullable | undefined; html: Nullable | undefined; }>; head(): any; }'.

Here is my current code snippet:

<script lang="ts">
import { Context } from '@nuxt/types'
import { PostOrPage } from 'tryghost__content-api'

export default {
  async asyncData ({ app, params }: Context) {
    const post: PostOrPage = await app.$ghost.posts.read(
      {
        slug: params.slug
      },
      { include: 'tags' }
    )

    return {
      title: post.title,
      excerpt: post.excerpt,
      feature_image: post.feature_image,
      html: post.html
    }
  },

  head () {
    return {
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.excerpt
        }
      ]
    }
  }
}
</script>

I have attempted various solutions, such as utilizing data() to establish default values for each item, but so far, nothing has worked. Any suggestions or insights would be greatly appreciated.

Answer №1

If you're looking to add Typescript support to your Nuxt project, consider using a typescript plugin like nuxt-property-decorator. Without it, type checking and autocomplete won't be available.

For proper integration, make sure to include asyncData & fetch within the Component options.

@Component({
  asyncData (ctx) {
    ...
  }
})
export default class YourClass extends Vue {
...
}

Rather than placing them outside of the component as shown below:

@Component
export default class YourClass extends Vue {
  asyncData (ctx) {
    ...
  }
}

If you prefer to use asyncData() within your component class instead of setting the option, refer to this demo that showcases the usage of the npm module nuxt-property-decorator.

Answer №2

Below is the updated code with the recommended changes from @nonNumericalFloat :

import { Component, Vue } from 'nuxt-property-decorator'
import { Context } from '@nuxt/types'
import { PostOrPage } from 'tryghost__content-api'

import Title from '~/components/Title.vue'

@Component({
  components: {
    Title
  }
})
export default class Page extends Vue {
  post!: PostOrPage

  async asyncData ({ app, params }: Context) {
    const post: PostOrPage = await app.$ghost.posts.read(
      {
        slug: params.slug
      },
      { include: 'tags' }
    )

    return {
      post
    }
  }

  head () {
    return {
      title: this.post.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.post.excerpt
        }
      ]
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...

At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left. Is there a way to achieve this using ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

Function used to update database through AJAX technology

I have implemented a PHP script to update my database using AJAX, and it is working correctly after being tested. To pass the required two variables to the PHP script for updating the database, I created a JavaScript function that utilizes AJAX to call the ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

Utilizing the mobile navigation layout for desktop screens without the need to adjust breakpoints

Having created a responsive site with common breakpoints established in SCSS as mixins, I am now seeking to implement the mobile breakpoint for a single page on desktop view only. Initially, my plan was to create a 'forced-mobile' class by exten ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

Attempting to create a slider utilizing jQuery

I'm currently working on creating a slider using jquery. I have downloaded the cycle plugin for the slider and included it in my file. The slider consists of 7 pictures. Below is the code I am using, can someone please help me identify any issues? &l ...

I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed. Within this component, I'm utilizing the UsersList.vue compo ...

Sliding the container with a width adjustment and left margin fails to display all images

In the provided HTML code below, there is a functionality to move images horizontally by clicking on buttons: $(document).ready(function() { calculate_width(); $('#moveleft').click(function() { var loga = $('#marki #loga'); ...

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

JSP checkbox functionality

I have been attempting to solve this issue since last night, but I am struggling and need some help. There are two pages, named name.jsp and roll.jsp. In name.jsp, there are two input text boxes and one checkbox. After entering data in the text boxes and ...

JavaScript for rotating an element upon button click

My webpage design <div id="yabanner"> <img src="img/ok.jpg"> </div> <button>Click Me</button> <button>Click Me</button> <button>Click Me</button> My script code var button = document.getElementsBy ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Issues with data communication in AJAX and Node JS/Express post requests

I'm currently exploring Node.js and I'm running into an issue with app.post. Everything seems to be working fine, as I can see the console log whenever the action is executed. However, the data sent by AJAX from main.js does not seem to be receiv ...

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

Bug found in React Native when navigating between screens causing the screen size to shrink

Check out the image below. https://i.stack.imgur.com/t04Vv.png Issue: Whenever I switch to a new scene, the previous screen appears to shrink or move upwards. This behavior is not consistent with the usual user experience seen on Apple apps - any thought ...

AgGrid supports multi-line content within its cells

I attempted to utilize this solution, however, it is not functioning properly for me. While it does resize the column height correctly, the text is still not wrapped as expected. Ag-Grid - Row with multiline text let gridOptions = { columnDefs: column ...

Detecting drag events between connected angular ui-trees is a complex yet achievable task

How can I trigger an action when an item is dragged from tree#1 to tree#2 and dropped? I want to make a specific HTTP call to save the transferred item. I have successfully implemented actions within one tree using the 'dropped' event, but strugg ...