Search code examples
javascriptvue.jscomponentsvuejs2nuxt.js

I want to load and populate the data for each component in vue.js (nuxt.js)


I start the project as follows.

vue init nuxt/express

my directory is...

components
|- slider.vue
|- list.vue
pages
|- index.vue

and components is,

index.vue

<template>
  <my-slider/>
  <my-list/>
</template>
<script>
import MySlider from '~components/slider'
import MyList from '~components/list'
export default {
  components: {
    MySlider,
    MyList
  },
   asyncData () {
    ... axios get ...
    return {
        img: response.data.img
    }
  }
}
</script>

I set up the following structure.

If a GET / request occurs,

I want to import data from the database in each component (MySlider, MyList).

  1. Does each component (MySlider, MyList) need to make an axios request from asyncData ()? Should I make an axios request from the index component asyncData ()?
  2. How do I set the data to initialize the axios response data after the request?

Solution

  • You decide how to set up your data. If you are using the same data in both subcomponents, I would fetch them from the parent component, and send it to the MySlider and MyList components using properties.

    If the data in both components have nothing to do with one another, I would probably try and keep these components as loosely coupled as possible, and just get them to fetch their data when they require it.

    Have a look at VueJS's lifecycle hooks to see how you can hook into any lifecycle event that happens on your component; these hooks allow you to go fetch your data as soon as it is required (read: as soon as your component is created / mounted / whatever you desire): https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks