Vue Router Props

Vue Router Props

I have been working on a basic e-commerce application for managing in-person order taking and creating a proper sales data store. I'm still learning Vue Js, following @academind course on Udemy.

Yesterday, I ran into a problem. I had a component, to allow the user to edit the prices of the products, to allow for price updates in our Nigerian economy which is under constant inflationary pressure. My plan was for this component to show placeholder values from the current values as stored in the Firebase Realtime Database.

To achieve this, I had initially made an api call to get these values from the database. However, this was not very performant, as the values would show undefined for a while, before the api call was completed, and then update. Screenshot from 2021-01-15 13-43-36.png

This component, was being loaded through a router-view component. I thus, had the idea that since an api call was already being made to populate the home page with all the items currently in the database, I could somehow utilize the result of that api call to populate the component in question. To achieve this, I would need to pass about four (4) values to the component.

Lucky for me, after some stackOverflow surfing and Vue docs browsing, I found a solution. In my App.vue where the component was being loaded by a $router.push function, I could pass an object, rather than just a string for the destination route. In this object, I could put in the values I needed as props, as query strings. App.vue

``` editProduct(id, product) {
      this.$router.push({
        name: 'edit',
        params: {id: id},
        query: {
          name: product.productName,
          unit_price: (product.unitPrice),
          carton_price: product.cartonPrice,
          half_carton_price: product.halfCartonPrice
        }
      })
    }

This required me to go back to my router.js file and update my route definition, to accept those props, as well as go back to my EditProduct component and accept them.

router.js

{path: '/edit/:id',
        name: 'edit',
        component: EditProduct,
        props: route => ({
            name: route.query.name,
            unit_price: route.query.unit_price,
            carton_price: route.query.carton_price,
            half_carton_price: route.query.half_carton_price
        })
        }

EditProduct.vue

props: ['name', 'unit_price', 'carton_price', 'half_carton_price']

Doing this, I was able to totally eliminate an unnecessary api call, and also make my EditProduct component more reusable, as it would only require props, and not parameters.