[Vuejs]-Select random item from array in Nuxt.js on the server only

0πŸ‘

βœ…

In page.vue I used asyncData to set the data server side during render, like so:

export default {
    components: {
         'component'
    },
    data(){
         return {
             city: ''
         }
    },
    asyncData (context){
         let cities = ["Rome", "Amsterdam", "Paris", "Berlin", "London", "Athens", "Madrid"];
         const city = cities[Math.floor(Math.random()*cities.length)];
         return {
              city: city
         }
    }
}

Now that we have the variable city with a random city, pass this onto a component using either a prop or by using this.$parent.city in the component.

πŸ‘€tkon99

Leave a comment