VueRouter Basic tutorial series 🎉

There are two opportunities to request server data in Vue:

  1. Before route navigation is complete: Initiate a request during the lifecycle of the route.
  2. After routing navigation is complete: Initiate a request during the routing component lifecycle.
{
    methods: {
        getPost() {
            this.loading = false;
            fetch('/data').then(res= > {
                this.data = res.data;
                this.loading = true; }); }}}Copy the code

Before routing navigation is complete

Requests are initiated in routing lifecycle hooks, primarily in beforeEach or beforeRouteEnter, beforeRouteUpdate.

export default {
  data() {
    return {
      post: null.error: null,}},beforeRouteEnter(to, from, next) {
    getPost(to.params.id, (err, post) = > {
      next(vm= > vm.setData(err, post))
    })
  },
  // The component is rendered before the route changes
  // The logic is slightly different
  async beforeRouteUpdate(to, from) {
    this.post = null
    try {
      this.post = await getPost(to.params.id)
    } catch (error) {
      this.error = error.toString()
    }
  },
}
Copy the code

Route navigation is complete

Requests are made in the lifecycle hooks of the routing component, primarily in Created.

 {
    data() {
        return {
            loading: false.post: null.error: null,}},created() {
        // watch route parameters to get data again
        this.$watch(
            () = > this.$route.params,
            () = > {
                this.fetchData()
            },
            // Get data after component is created.
            // The data has been observed
            { immediate: true}}})Copy the code