yeti blue
yeti blue

Reputation: 271

Best solution for getting {id} from url?

I'm trying to create a feature where individuals can create Listings, and other users can submit an application. ATM I can't quite figure out how to get the ID from the URL of:

'http://localhost:3000/listings/2/'

I have a hunch that this needs Vue router and $route.params.id? Basically I want in my form.listing the ID of the listing in which users are applying to. In this case it would be '2'

My folder structure is .../listings/_id/index.vue

This is my backend for the user_applications model in DRF:

 listing = models.ForeignKey(Listings,  on_delete=models.CASCADE, default="1")

Here's the frontend: I was hoping I could use the props value in script, but it seems like it only works in template, oh well.

  data: () => ({
    form: {
      role: null,
      company: null,
      status: "Pending"
      // listing: listings.id
    }
  }),

  props: ["listings"],
  computed: {
    ...mapGetters(["loggedInUser"])
  },

  methods: {
    submit() {
      this.$axios
        .post("/api/v1/apps/", this.form)
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }

Upvotes: 0

Views: 1703

Answers (2)

selfagency
selfagency

Reputation: 1578

Yes, it's as easy as this.$route.params.id. You can invoke $route.params.id directly in your template, without using this. Don't use arrow functions in your component, though! They strip out the value of this! Also, all props and data attributes are available on this as well. So this.listing and this.$route are available, not only in your template, but in your Vue component's methods and computed properties, as well.

Try this approach, instead:

  data() {
    return {
      form: {
        role: null,
        company: null,
        status: "Pending",
        listing: this.listings.id
      }
    }
  },

Upvotes: 0

Victory
Victory

Reputation: 5890

You are on the right track when thinking of using VueRouter. Lets say that your component name is Listing.

import VueRouter from 'vue-router';
import Listing form './path/to/ListingComponent.vue';

const router = new VueRouter({
  routes: [
    {
      path: '/listing/:id',
      component: Listing,
      // return parms.id as listingId for the `Listing` component.
      props: route => ({ listingId: route.params.id })
    }
  ]
})

In this way you have listingId passed to the props of Listing.

Upvotes: 1

Related Questions