How to get the route params and pass it as props for named views? - vue-router

My application have navbar with back button. The navbarTop is a named views, so I can have different navbar for each route, and the navbar needs props backRoute.
I define the back route like this:
{
path: '/:id',
name: 'orders detail',
components: {
default: OrderDetail,
navbarTop: Navbar,
},
props: {
navbarTop: {
backRoute: { name: 'orders' },
title: 'Order Detail',
},
default: true,
},
},
{
path: '/:id/request-cancel',
name: 'orders request cancel',
components: {
default: OrderRequestCancel,
navbarTop: Navbar,
},
props: {
navbarTop: {
backRoute: { name: 'orders', params: {id: ???} }, // how to get the id here?
title: 'Request Cancel',
},
default: true,
},
},
Is it possible to get the id in route and pass it as prop to the component?
The NavbarTop is named view and is used in many routes, so I can't update the back route from OrderRequestCancel component.

We can use Function Mode
props: {
navbarTop: route => ({
backRoute: { name: 'order detail', params: { id: route.params.id } },
title: 'Request Cancel',
}),
default: true,
},
Thank you #Yom S. for the hint.

Related

How to pass Integer value in Vue router 4 props

I'm working with vue router 4, I've got an error when I'm passing post id to post details page via router props, it
runtime-core.esm-bundler.js:38 [Vue warn]: Invalid prop: type check failed for prop "destinationId". Expected Number with value 1, got String with value "1"
Now my questions is how can I pass the id as Integer? it's passing as String.
Here is my router file:
routes: [
{
path: '/',
name: 'HomeRoute',
component: HomeView
},
{
path: '/details/:slug/',
name: 'DestinationDetails',
component: () => import('../views/DestinationDetails.vue'),
props: route => ({...route.params , slug: route.params.slug}),
children: [
{
path: ':exprienceSlug',
name: 'experience.show',
component: () => import('../views/PlaceDetails.vue'),
props: route => ({...route.params,}),
},
]
},
{
path: '/:pathMatch(.*)*',
name: "NotFound",
component: () => import('../views/NotFound.vue'),
}
]
And Here is my Post file where form I'm passing the params via router-link tag
<router-link class="col-md-3"
v-for="experience in destination.experiences"
:key="experience.id"
:to="{name: 'experience.show', params: {exprienceSlug: experience.slug, destinationId: destination.id}}">
<PlacesCard :places="experience"/>
</router-link>
And this is post single page where I'm catching the id and fetch the posts.
props: {
destinationId: {
type: Number,
required: true,
default: 0,
},
exprienceSlug: {
type: String,
required: true,
},
},
computed: {
destination(){
return storeData.destinations.find(
destination => destination.id == this.destinationId
)
},
experience(){
return this.destination.experiences.find(
experience => experience.slug == this.exprienceSlug
)
}
},
route.params are of type string | string[].
But you can change that by parsing the params:
children: [
{
path: ':exprienceSlug',
name: 'experience.show',
component: () => import('../views/PlaceDetails.vue'),
props: ({ params }: Route) => ({
...route.params,
destinationId: Number(params.destinationId)
}),
},
]

Vue router-link pass prop getting undefined

This is how I passed the prop:
<router-link :to="{ name: 'Cart', params: { payment_method: 'cod' } }">
Router component is like this:
{
path: "/cart",
name: "Cart",
component: Cart,
props: true,
meta: {
requiresAuth: true,
},
},
in the receiving route, Props:
props: {
payment_method: String,
},
I am getting undefined as value for payment_method. what is wrong here?
Change your router component path to:
{
path: "/cart/:payment_method",
name: "Cart",
component: Cart,
props: true,
meta: {
requiresAuth: true,
},
},
Try to set payment_method as slug in route with props:true and catch the route's prop directly in data of vue instance
<router-link :to="{ name: 'Cart', params: { payment_method: 'cod' } }">
{
path: "/cart/:payment_method",
name: "Cart",
component: Cart,
props: true,
meta: {
requiresAuth: true,
},
},
catch directly in data
data: function () {
return {
payment_method: this.$route.params.payment_method,
};
},
This will resolve your problem

Vue Router Dynamic Route access to PARAMS

I work with dynamic routes similar a this form:
router.js
...
{
path: "/init/clients/moral-person/:company",
name: "moralPerson",
component: () => import('../MoralPerson.vue'),
meta: {
auth: true,
breadcrumb: [
{ text: "Init", disabled: false, name: "init" },
{ text: "Clients", disabled: true, name: "" },
{ text: "Moral Person", disabled: false, name: "crudMoralPerson"},
{ text: "Company", disabled: true, name: "", icon: "fas fa-dollar-sign"},
]
}
}
...
NOTE: The part of breadcrumb is render for other component.
When I do router.push is this:
Some File
...
this.$router.push({
name: "moralPerson",
params: { company: this.nameCompany }
});
...
Finally looks similar this:
I try to use the this.router.params, in this case :company and colocate in the part blue I mark or here:
router.js
...
// in this line
{ text: :company, disabled: true, name: "", icon: "fas fa-dollar-sign"},
...
My question is, How access this param and colocate in this part I need?
EDIT
I try with:
...
{ text: this.$route.params.empresa, disabled: true, name: "", icon: "fas fa-dollar-sign"},
...
And always send me:
Let see, in your router configuration you are indicating that moralPerson component will receive a param called company, isn't it?
this.$router.push({
name: "moralPerson",
params: { company: this.nameCompany }
});
The code above is correct, you must call your component using name if you want to pass some params.
To access this param you must do the following, mainly inside created lifecycle function:
this.$route.params.company
I hope this could help you
Try something like this:
{
path: '/init/clients/moral-person/:company'
name: 'moralPerson',
component: () => import('../MoralPerson.vue'),
meta() {
return {
auth: true,
breadcrumb: [
{ text: 'Init', disabled: false, name: 'init' },
{ text: 'Clients', disabled: true, name: '' },
{ text: 'Moral Person', disabled: false, name: 'crudMoralPerson' },
{ text: this.params.company, disabled: true, name: '', icon: 'fas fa-dollar-sign' },
],
};
},
},
When you call the meta function, try this this.$route.meta(), because now the meta property is a function.

vue-router returns 'function%20%' in url instead of param

So I'm showing some bread-crumbs like so..
<router-link to="/" class="breadcrumb-item">Home</router-link>
<router-link :to="{name: 'provider-dashboard', params: { id: provider_id }}" class="breadcrumb-item">Provider Dashboard</router-link>
<router-link :to="{name: 'provider-account-dash', params: { provider_id: provider_id, id: account_id }}" class="breadcrumb-item">Account Dashboard</router-link>
<router-link :to="{name: 'resident-profile', params: { account_id: account_id, id: resident_id }}" class="breadcrumb-item">Resident Profile</router-link>
I'm setting the param values with computed props that look like so..
account_id: {
get() {
return this.$store.getters['AssessmentPlanForm/getAccountId'];
},
set(value) {
this.$store.dispatch('AssessmentPlanForm/setAccountId', value);
},
},
provider_id: {
get() {
return this.$store.getters['AssessmentPlanForm/getProviderId'];
},
set(value) {
this.$store.dispatch('AssessmentPlanForm/setProviderId', value);
}
},
resident_id: {
get() {
return this.$store.getters['AssessmentPlanForm/getResidentId'];
},
set(value) {
this.$store.dispatch('AssessmentPlanForm/setResidentId', value);
},
},
I have confirmed that the values of the computed properties are correct, however when I click the router-link breadcrumb to go to desired location, the url shows users/function%20Number() instead of say users/18.
Why is this occurring and how can I get vue-router to properly render the parameter set by computed-prop?
Update from 1st comment
Here are the getters & no I'm not doing that for these attributes.
getId: (state) => {
return state.id;
},
getProviderId: (state) => {
return state.provider_id;
},
getEmployeeId: (state) => {
return state.employee_id;
},
getAccountId: (state) => {
return state.account_id;
},
getResidentId: (state) => {
return state.resident_id;
},
getSlug: (state) => {
return state.slug;
},
Update from 2nd comment
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [{
path: "/",
name: "home",
component: Splash,
prop: true
},
{
path: "/about",
name: "about",
component: About,
prop: true,
},
{
path: "/contact",
name: "contact",
component: ContactUs,
prop: true,
},
{
path: "/pricing",
name: "pricing",
component: Pricing,
prop: true,
},
{
path: "/faq",
name: "faq",
component: Faq,
prop: true
},
{
path: "/polls",
name: "polls",
component: Polls,
prop: true
},
{
path: "/login",
name: "login",
component: Login,
prop: true
},
{
path: "/provider-signup",
name: "provider-signup",
component: ProviderSignup,
prop: true
},
{
path: "/provider-dashboard/:id",
name: "provider-dashboard",
component: ProviderDash,
prop: true
},
{
path: "/providers/:id/edit",
name: "edit-provider",
component: EditProvider,
prop: true
},
{
path: "/provider/:id/employee-invitation",
name: "employee-invitation",
component: ProviderEmployeeInvite,
prop: true
},
{
path: "/employee-signup",
name: "employee-signup",
component: EmployeeSignup,
prop: true
},
{
path: "/employee-dashboard/:id",
name: "employee-dashboard",
component: EmployeeDash,
prop: true
},
{
path: "/employees/:id/edit",
name: "edit-employee",
component: EditEmployee,
prop: true
},
{
path: "/provider/:provider_id/employees",
name: "employees",
component: Employees,
prop: true
},
{
path: "/provider/:provider_id/accounts/new",
name: "provider-account-signup",
component: ProviderAccountSignup,
prop: true
},
{
path: "/providers/:provider_id/accounts/:id",
name: "provider-account-dash",
component: ProviderAccountDash,
prop: true
},
{
path: "/providers/:provider_id/accounts/:account_id/edit",
name: "edit-provider-account",
component: EditProviderAccount,
prop: true
},
.
.
.
]
});
So the answer was to fix a User error on my part. I forgot to assign the values of those attributes in a page I was working on.
The answer was to load the values of these attributes #created
retrieve(context, record_id) {
let resident_id = router.currentRoute.params.resident_id;
Axios.get(`/residents/${resident_id}/assessment_plan_forms/${record_id}`, {
headers: {
'Authorization': 'Bearer ' + window.$cookies.get('access_token'),
'x-amz-acl': 'public-read'
}
})
.then((response) => {
// let current_user = response.data.locals.current_user;
let provider = response.data.locals.provider;
let resident = response.data.locals.resident;
let account = response.data.locals.account;
let pdf_url = response.data.locals.pdf_url;
let date_of_record = response.data.locals.date_of_record;
let assessment_plan_form = response.data.locals.assessment_plan_form;
context.dispatch('AssessmentPlanForm/setId', assessment_plan_form.id, {
root: true
})
context.dispatch('AssessmentPlanForm/setProviderId', provider.id, {
root: true
})
context.dispatch('AssessmentPlanForm/setAccountId', account.id, {
root: true
})
context.dispatch('AssessmentPlanForm/setResidentId', resident.id, {
root: true
});
context.dispatch('AssessmentPlanForm/setPdfUrl', pdf_url, {
root: true
});
context.dispatch('AssessmentPlanForm/setDateOfRecord', date_of_record, {
root: true
});
context.dispatch('AssessmentPlanForm/setResidentSignature', resident.full_name, {
root: true
});
// redirect to show page
router.push({
name: 'show-assessment-plan',
params: {
resident_id: resident.id,
id: record_id
}
})
})
.catch((error) => {
console.log(error);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
And #retrieve gets called in the Created hook like:
methods: {
loadAssessmentPlan() {
this.$store.dispatch('AssessmentPlanForm/retrieve', this.$route.params.id)
},
},
created() {
this.loadAssessmentPlan();
},

vuejs router - this.$route is always empty on refresh

I'm trying to set the class nav-active to the correct nav element, based from what url you're directly accessing the webapp for the first time.
I have a few routes:
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: () => import('./views/Home.vue')
},
{
path: '/account',
name: 'account',
component: () => import('./views/Account.vue')
}
]
});
And this is my navigation bar component (NavBar):
export default {
name: 'NavBar',
components: {
NavLogo,
NavItem
},
data() {
return {
navItems: [
{ /* root navigation */
id: 0,
type: 'root',
name: 'home',
route: '/',
active: this.$route.name === 'home' },
{
id: 1,
type: 'root',
name: 'account',
route: '/account',
active: false
}
}
}
}
The state of the active boolean inside navItems determines whether the navigation element should have the nav-active class. I'm trying to use the current route to determine whether active should be true or false, by using it this way:
active: this.$route.name === 'account'
But once for example I enter this dashboard directly from: http://localhost:8000/account
this.$route's items are all empty and the path is always /
Help is much appreciated,
Thanks
You are not tracking this.$route.name changes by default with this approach.
Try creating a computed property that resolves to this.$route.name, and use this in your data property declaration. In fact, you can just stick the whole thing in a computed property, since you're unlikely to change this.
export default {
name: 'NavBar',
components: {
NavLogo,
NavItem
},
computed: {
routeName(){
return this.$route.name
},
navItems(){
return [
{ /* root navigation */
id: 0,
type: 'root',
name: 'home',
route: '/',
active: this.routeName === 'home' },
{
id: 1,
type: 'root',
name: 'account',
route: '/account',
active: false
}
]
}
}
}