vue.js - beforeEnter 将数据传递给路由组件

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

我有以下 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

问题1

  • 您可以从 Router 设置 Vue 组件的 props 属性吗?

问题2

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

最佳答案

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 Hook 中获取数据,并将其设置为您在 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 Hook 中,您将拥有如下内容:

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

关于vue.js - beforeEnter 将数据传递给路由组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56725120/

相关文章:

vue.js - 如何在没有CORS错误的情况下在Vue CLI中加载JSON

javascript - 如何在VUE组件的Scoped区域中使用JSON数据

javascript - Vue 将变量与兄弟组件数据进行比较

javascript - vuejs2 beforeUpdate 生命周期钩子(Hook)触发两次

javascript - vuejs 2观察不起作用

javascript - vue v-for 对象 Prop

javascript - 如何根据html vue js中的选择选项添加行?

javascript - 如何在 Vue.JS 中使用 axios 方法填充组件的数据

vue.js - vue-router beforeRouteUpdate 切换时使用旧参数

javascript - JQuery 不能与 Vuejs 一起使用