我已经设置了视图路由器:
router.map({
'/tracks/:id': {
component: SingleTrack
}
})
这是我的组件(使用硬编码的URL):
var SingleTrack = Vue.component('track', {
template: '#track-template',
data: function() {
return {
track: ''
}
},
ready: function() {
this.$http.get('//api.trax.dev/tracks/1', function (data) {
this.$set('track', data.track)
})
}
});
如何将url /:id传递给$http.get
字符串的末尾,以便在加载该路由时动态获取正确的数据,如:
ready: function(id) {
this.$http.get('//api.trax.dev/tracks/' + id, function (data) {
this.$set('track', data.track)
})
}
答案 0 :(得分:5)
您应该能够从组件$route
属性中获取route参数:
var itemId = this.$route.params.id;
this.$http.get('//api.trax.dev/tracks/' + itemId, function (data) {
this.$set('track', data.track)
})
中查看更多详情
答案 1 :(得分:1)
最佳实践:
index.js(路由器)
{
path: '/tracks/:id',
name: 'SingleTrack',
component: SingleTrack,
props: (route) => {
const id = Number.parseInt(route.params.id);
return { id }
},
}
SingleTrack.vue
props: {
id: {
type: Number,
required: true,
},
},
mounted(){
this.$http.get('//api.trax.dev/tracks/' +this.id, function (data) {
this.$set('track', data.track)
})
}