Experience dynamic data transformations with Vue's server-side rendering feature

Incorporating Vue into server-side rendering presents a challenge when the content data within the template needs to be fetched from another CMS server.

<template>
  <h1>{{ content.heading }}</h1>
</template>

<script>
  export default {
    data() {
      return {
        content: {
          heading: ''
        }
      }
    },
    created() {
      axios
        .get(CONTENT_RESOURCE)
        .then(content => this.content = content);
    }
  }
</script>

Since the axios.get method is asynchronous, the server may send empty content before the request is complete.

To retrieve content using curl:

curl 'URL';
# It returns <h1></h1>,
# but I need <h1>Something here</h1>

How can I ensure that the server-side rendering includes the CMS content data?

Answer №1

Based on the example provided in vue-hackernews-2.0, the src/server-entry.js file will identify the preFetch function within the current route component.

Therefore, simply include a preFetch function in the current route component and store the data in the Vuex store.

<template>
  <h1>{{ content.heading }}</h1>
</template>

<script>
  const fetchContent = store => 
    axios
      .get(CONTENT_RESOURCE)
      .then(content => store.dispatch('SAVE_CONTENT', content));

  export default {
    computed: {
      content() {
        return this.$store.YOUR_CONTENT_KEY_NAME
      }
    },
    preFetch: fetchContent,   // For server side render
    beforeCreate() {          // For client side render
      fetchContent(this.$store);
    }
  }
</script>

Answer №2

To properly update the code, you need to implement the following changes:

let example = new Vue({
    el: '#example',
    data:{
         content : {title: ""}
    },
    beforeMount() {
      let self = this;
      setTimeout(function(){
          self.content.title = "HELLO"
      }, 100)
    }
})

You can view a working demo here.

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

What is the best way to retrieve and parse XML using node.js?

Is there a way to fetch an XML file from the internet using node.js, and then parse it into a JavaScript object? I've looked through the npm registry but can only find examples on parsing XML strings, not fetching them. ...

The error message "npm run dev Error: The derived class t must have a greater number of constructor arguments than its base class" is indicating a mismatch in the number of constructor arguments between

When using vue with Laravel 5.8 in Vagrant, I encountered an error while running npm run development as shown below: root@ubuntu-xenial:/vagrant/webroot# npm run development > @ development /vagrant/webroot > cross-env NODE_ENV=development node_modu ...

Centered iframe within a div

I am trying to center my iframe within a white box and need some assistance with this. I want the iframe to be in the middle of the white box rather than its current position at the moment. game1.html: <html> <head> <title>R ...

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

Enhancing user experience: Implementing specific actions when reconnecting with Socket.io after a disconnection

I am working on a game using node.js and socket.io. The code I have written is quite simple. The game starts animating as soon as it connects to the server and continues to do so. My main concern is ensuring that the game handles network and server disco ...

Is combining Passport.js Google authentication with JWT a logical choice?

I am currently working on integrating Google Login with Passport.js into my MERN stack application. However, I have created this middleware for JWT authentication: const jwt = require("jsonwebtoken"); const config = require("config"); module.exports = a ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

"Vue is throwing an error because it cannot set the property '$offlineStorage' on an undefined object. How can this issue be resolved

While working on my vue ionic app, I integrated the plugin available at https://github.com/filrak/vue-offline. However, upon installing the plugin, an error was encountered: vue-offline.js?bf4e:193 Uncaught TypeError: Cannot set property '$offlineStor ...

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

generating a new item using Mongoose searches

How can I generate an object based on queries' results? The table in the meals operates using database queries. How do I handle this if the queries are asynchronous? const getQueryResult = () => { Dinner1300.count().exec(function (err, count) ...

Exploring the world of Ajax and managing cookies

I am facing an issue with setting cookies in my login form using ajax when the "remember me" checkbox is checked. Despite having code to handle this scenario, the cookies are not getting set properly. After executing var_dump($_COOKIE), I see that only the ...

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

Styles not applied to React.js components when page is refreshed

I'm encountering an issue while using React in combination with react-router and material ui. Upon the initial page load, everything appears as expected. However, if I refresh the page, all styles seem to disappear. If I make changes to the code and ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

Confirming Bootstrap - Implement an onConfirm method for element attributes

I am looking to add a JavaScript function to my confirmation button. I have created the elements off-page and fetched them using ajax, so it is crucial that I can set the function in-properties rather than via $('#id').confirmation() So far, I h ...

We regret to inform you that there has been an integration error with Zoom SDK 2,3,5. You have reached the limit set by Zoom. Please verify

I'm currently working on integrating zoom web SDK version 2.3.5 into my Vue app that uses Laravel as the backend. However, I've encountered an error when trying to join a meeting. Here is the error message I received: You have been limited by Z ...

Using a variable in VueJS to reference an external template file

Is there a way for me to choose a component template based on the client I am working with? I have set the client ID in the env file and what I am looking for is something similar to the following: <template :src="'../themes/' + process.env.V ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here. Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars. Here i ...