5

Problem: I have a component that needs a boolean value optionally passed to it as part of a call from within the view app and from an external app. When I invoke the router directly I can pass the boolean with no issues but if I route by using the actual URL I get a parse warning. To prevent the warning should I be using a string instead and parse it myself?

Router:

export default new Router({
  routes: [
    {
      path: '/foo',
      name: 'Foo',
      component: Foo,
      props: (route) => ({ booleanParam: route.query.booleanParam })
    }
  ]
})

Component:

<template>
    <div>
        BooleanParam: {{booleanParam}}
    </div>
</template>

<script>
export default {
    name: 'Foo',
    props: {
        booleanParam: {
            type: Boolean,
            required: false
        }
    }
}
</script>

Works:

router.push( { name: 'Foo', query: { booleanParam: true } })

Generates Warning:

http://localhost:8080/foo?booleanParam=true

Warning:

[Vue warn]: Invalid prop: type check failed for prop "booleanParam". Expected Boolean, got String.

2 Answers 2

7

If a boolean is required by the component then parse the value as a Boolean before setting this as a prop:

props: (route) => ({ booleanParam: (route.query.booleanParam === 'true') })

This way the correct type is ensured.


EDIT: As noted in the comment by the OP to support both String and Boolean the parameter could be converted to String to ensure both types work:

props: (route) => ({ booleanParam: (String(route.query.booleanParam). toLowerCase() === 'true') })
Sign up to request clarification or add additional context in comments.

1 Comment

One caveat to this, if you're going to be doing a router.push with the boolean paramter you should do the following to support both paths: props: (route) => ({ booleanParam: (route.query.booleanParam === 'true' || route.query.booleanParam === true) })
0

have you try this

   const router = new VueRouter({
      routes: [
        { 
        path: '/foo',
        name:"Foo"
        component: Foo, props: (route) => ({ query: route.query.q }) }
      ]
    })

    OR

    {path:'/foo/:booleanParam', name:'Foo', component: Foo  }

1 Comment

I think the first part is what I've got in my question above. Since the parameter is optional foo/:boolean param won't work for my use case, hence the use of the query param.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.