[Vuejs]-Get specific data from vuex store while using a route

4πŸ‘

βœ…

First, by adding props: true to your route object, you can pass in the route parameters as props to your PhysicianProfile component

    {
        path: '/physicians/profile/:firstName-:lastName-:designation',
        name: 'pd-profile',
        component: PhysicianProfile,
        props: true
    },

Then you can add those three props to your PhysicianProfile component, and set up a Vuex getter to fetch the physician:

getters: {
  // ...
  getPhysicianByDetails: (state) => (firstName, lastName, designation) => {
    return state.physicians.find(phys => phys.firstName === firstName && phys.lastName === lastName && phys.designation === designation)
  }
}

Check these out for further reading

https://medium.com/vue-by-example/learn-quickly-passing-params-as-props-with-vue-router-f4905735b747

https://vuex.vuejs.org/guide/getters.html

πŸ‘€Jeff

1πŸ‘

You can pass props through the URL, in this case, the Physician ID. Then you can fetch the physician in the created lifecycle hook πŸ™‚

To make the explanation a bit easier I’ll add an id to your path (/physician/profile/id/firstName-lastName-designation). You can change the find method in the created hook to suite your needs πŸ™‚

// Router
  {
     path: '/physicians/profile/:id/:firstName-:lastName-:designation',
     name: 'pd-profile',
     component: PhysicianProfile,
     props: true
  },

You then need to set the props and fetch the physician in PhisicianProfile.vue:

<template>
    <div class="physician-profile">
        <h1 class="mb-5">{{ msg }}</h1>
    </div>
</template>

<script>
    export default {
        name: 'pd-profile',
        props: {
            id: {
                required: true
            },
            // rest of the props if needed
        },
        data () {
            return {
                msg: 'Physician Profile',
            }
        },

        created () {
            // Fetch the physician with based on this.id
            const physician = this.$store.state.physicians.find((physician) => { return physician.id == this.id })
            // Do something with physician (set to data and use in template)
        }
    }
</script>

For more information about passing props, check out the vue router documentation πŸ™‚

πŸ‘€RAH

Leave a comment