user3711357
user3711357

Reputation: 1635

How to use "data" or "methods" result to VueRouter prop

I have simple menu tabs router as follow:

Tab 1 | Tab 2 | Tab 3

Routes are attached with individual component to each tab as example below.

const router = new VueRouter({
  routes: [
    { path: '/views/type1', component: Type1, props: { listname: value} }
  ]
})

Problem: How route[] prop modify to take the value from "data" of vue. Basically, one of the component accept property as 'Array' and I need to pull those data from service and attach to component.

routes: [
        { path: '/views/type1', component: Type1, props: { collection: *[retrieve from service and attach here]*} }
      ]

//collection is not able to bind from "methods" or "data" , it only accepts static data.

Upvotes: 0

Views: 291

Answers (1)

tony19
tony19

Reputation: 138676

The props field of Vue Router does not hold properties to be passed to the rendered view component, but rather it is a Boolean flag (or a hash/map of view names to Boolean flags) that tells Vue Router to pass any route parameters (parsed from the path) as properties to the component.

For example, given the following:

  • route config:

    {
      path: '/user/:name/:uid',
      component: User,
      props: true
    }
    
  • User component definition:

    export default {
      props: ['name', 'uid']
    }
    
  • URL:

    /user/john/123
    

Then, User would be rendered with name set to john and uid set to 123, equivalent to this:

<User :name="john" :uid="123" />

If you need to initialize a view with server data, you could wrap the target component (e.g., with Type1View) that you initialize after you've fetched the data. In the example below, Type1.list is bound to a local list data variable. When Type1View mounts, we fetch data from the server, and save the result in list, which also updates Type1.list.

<template>
  <div>
    <Type1 :list="list" />
  </div>
</template>

<script>
export default {
  name: 'Type1View',
  data() {
    return {
      list: []
    }
  },
  async mounted() {
    const data = await this.fetchData();
    this.list = data.list;
  }
}
</script>

Upvotes: 2

Related Questions