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