admin管理员组

文章数量:1327996

I have have view router set up:

router.map({
    '/tracks/:id': {
        ponent: SingleTrack
    }
})

And this is my ponent (which works with a hard coded URL):

var SingleTrack = Vueponent('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)
        })
    }
});

How do I pass the url/:id to the end of the $http.get string so i can grab the correct data dynamically when that route in loaded, something like:

ready: function(id) {
    this.$http.get('//api.trax.dev/tracks/' + id, function (data) {
        this.$set('track', data.track)
    })
}

I have have view router set up:

router.map({
    '/tracks/:id': {
        ponent: SingleTrack
    }
})

And this is my ponent (which works with a hard coded URL):

var SingleTrack = Vue.ponent('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)
        })
    }
});

How do I pass the url/:id to the end of the $http.get string so i can grab the correct data dynamically when that route in loaded, something like:

ready: function(id) {
    this.$http.get('//api.trax.dev/tracks/' + id, function (data) {
        this.$set('track', data.track)
    })
}
Share Improve this question asked Dec 3, 2015 at 16:00 Jack BarhamJack Barham 3,21912 gold badges44 silver badges64 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You should be able to get the route parameter from the ponent $route property :

var itemId = this.$route.params.id;
this.$http.get('//api.trax.dev/tracks/' + itemId, function (data) {
    this.$set('track', data.track)
})

See more details in vue.js router documentation

For Best Practises:

index.js(router)

{
    path: '/tracks/:id',
    name: 'SingleTrack',
    ponent: 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)
 })
}

本文标签: javascriptHow do I pass a dynamic page id to httpget url in VuejsStack Overflow