Kendall
Kendall

Reputation: 5255

passing data to route's component beforeEnter

I have the following VueRouter route

{
  path: '/playlists/:id',
  name: 'videos',
  component: Video,
  props: {
    videos: [],
  },
  beforeEnter(to, from, next) {
    Vue.axios
      .get('/playlistitems?playlistId='.concat(to.params.id))
      .then((response) => {
        to.params.videos = response.data
        next((vm) => {
          console.log(vm)
          vm.videos = response.data
        })
      })
      .catch((err) => console.log('error', err))
  },
}

When the route is entered into everything executes as expected but I'm not sure how to pass the response.data to the route's component Videos

Question 1

Question 2

Upvotes: 2

Views: 3165

Answers (1)

Andrei Gătej
Andrei Gătej

Reputation: 11979

1)

This might not be the most elegant approach, but here's a way to achieve that:

let videos = [];

export default new Router({ ... });

{
      path: '/playlists/:id',
      name: 'videos',
      component: Video,
      props: route => ({ videos }),
      beforeEnter (to, from, next) {
        Vue.axios.get('/playlistitems?playlistId='.concat(to.params.id))
          .then((response) => {
            // Now the data will be available when the props will be initialized
            videos = response.data
            next()
          })
          .catch((err) => console.log('error', err))
      }
    }

// Videos.vue

props: {
    videos: Array
  },

2) IMHO, it would be easier if you could encapsulate the logic in the component. What do I mean by that is that you could fetch your data in the created hook and set it to a variable that you defined in your data function.

 data() {
    return {
      videos: []
    }
  },

  created () {
    Vue.axios.get('/playlistitems?playlistId='.concat(this.$route.params.id))
    .then((response) => {
      this.videos = response.data;
    })
    .catch((err) => console.log('error', err))
  },

Another approach, which may be suitable or not, depending on what you're working on, would be to have a parent component that fetches multiple playlists which could be stored in vuex. Thus, you would have another component that handles playlists/:id. Within this last mentioned component, in your created hook, you would have something like this:

created () {
    this.$store.commit('playlist/SET_CURRENT_PLAYLIST_ID', this.$route.params.id);
    this.videos = this.$store.getters['playlits/getVideosByPlaylistId'];
  },

Upvotes: 2

Related Questions