Emil Majer
Emil Majer

Reputation: 173

Vue + Typescript vue-router and type of params

I'm trying to send some data from one component to other, but I have some problem with types. This is my code:

const someData: object = {
   param1: 'param1',
   param2: 'param2',
   array: [{},{}]
}
this.$router.push({ name: 'SomePage', params: { someData } }) 

I get the data this way:

  get param1 (): string {
    return this.$route.params.someData['param1']
  }
  get param2 (): string {
    return this.$route.params.someData['param2']
  }
  get array (): Array<object> {
    return this.$route.params.someData['array']
  }

And the error from console:

Argument of type '{ name: string; params: { someData: object; }; }' is not assignable to parameter of type 'RawLocation'.
  Type '{ name: string; params: { someData: object; }; }' is not assignable to type 'Location'.
    Types of property 'params' are incompatible.
      Type '{ someData: object; }' is not assignable to type 'Dictionary<string>'.
        Property 'someData' is incompatible with index signature.
          Type 'object' is not assignable to type 'string'.

It works only if I put type any to someData, but I don't won't to use it. How can I solve this problem? What is this 'Location' and 'RawLocation' type?

Upvotes: 8

Views: 19329

Answers (1)

Alireza Varmaghani
Alireza Varmaghani

Reputation: 396

Just what you can pass through pages as query parameters is a string type, not anything else. it means you can't send array by a query parameter. you should change all your params to string

   const someData: object = {
      param1: 'stringType',
      param2: 'stringType',
      ...
   }
   this.$router.push({ name: 'SomePage', params: { someData } })

Instead of query parameter by vux you can save and datatype and use it everywhere you want, in my opening, I would be much better because at the same time your can manage passed data by your own

and about you @MagnusTeekivi you can cast it to string after than you can use it, like this

`this.$router.push({ name: 'user', params: { userId.toString() })`

Upvotes: 4

Related Questions