简体   繁体   中英

VueJS: Fetch data before and after loading a component

I am new to VueJS and working on a component and want to fetch some data from an API before the corresponding route is loaded; only then the component should load. Once the component is created, I have to call another API that takes as input the data obtained from first API. Here is my component script:

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  created () {
     // it gives length = 0 but it should have been categories.length
      console.log(this.categories.length);

    // Call getImage method
    loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {}
}

I tried using mounted hook but it does not work. However if I watch the categories property and call fetch image method, it works. I don't think using watchers is the best approach here. Any thoughts?

Move your call to get additional information into a method and call that method from next .

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
        vm.getMoreStuff()
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {
    getMoreStuff(){
      console.log(this.categories.length);

      // Call getImage method
      loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
    }
  }
}

Alternatively, do it in the callback for getCategories.

loginService.getCategories()
  .then(res => {
    vm.categories = res.data.categories;
    loginService.getImage(vm.categories.length)
      .then(res => //handle images then call next())
  })
  .catch(err => //handle err)

Or if you are using a pre-compiler that handles async/await

async beforeRouteEnter(to, from, next){
  try{
    const categoryResponse = await loginService.getCategories()
    const categories = categoryResponse.data.categories
    const imageResponse= await loginService.getImage(categories.length)
    next(vm => {
      vm.categories = categories 
      vm.images = imageResponse.data.images
    })

  } catch(err){
    //handle err
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM