【问题标题】:passing data to route's component beforeEnter将数据传递给路由的组件 beforeEnter
【发布时间】:2019-11-05 14:02:00
【问题描述】:

我有以下 VueRouter 路由

{
      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))
      }
    }

当输入路由时,一切都按预期执行,但我不确定如何将response.data 传递给路由的组件Videos

问题一

  • 能否从路由器设置 Vue 组件的 props 属性?

问题 2

  • 路由是动态路由。如果路由和组件已经加载并且动态参数发生变化......beforeEnter 仍然会触发吗?如果不是,我应该把我的数据获取逻辑放在哪里?我是否 watch 用于 Vue 组件 内的路由更改?

【问题讨论】:

    标签: vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    1)

    这可能不是最优雅的方法,但可以通过以下方式实现:

    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) 恕我直言,如果您可以将逻辑封装在组件中会更容易。 我的意思是您可以在created 挂钩中获取数据并将其设置为您在data 函数中定义的变量。

     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))
      },
    
    

    另一种方法,可能适合或不适合,具体取决于您正在处理的内容,它是有一个父组件来获取可以存储在 vuex 中的多个播放列表。 因此,您将拥有另一个处理playlists/:id 的组件。 在最后提到的这个组件中,在您的 created 挂钩中,您将拥有如下内容:

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

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2017-08-29
      • 2016-08-18
      • 2016-07-14
      • 2022-01-13
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2015-10-15
      相关资源
      最近更新 更多