基于组件的 vue 动态路由 (模仿react-router4)
<HistoryRouter> <div> <Route path="/contacts"> <Contacts :contacts=“contacts”></Contacts> </Route> <Route path="/contacts/:id"> <Contact></Contact> </Route> </div> </HistoryRouter> </template> <script> import {HistoryRouter, Route, RouterLink} from ‘vue-component-router’;
export default {
data () {
return {
contacts: [‘Contact 1’, ‘Contact 2’]
};
},
components: {
HistoryRouter,
Route,
Contacts: {
props: [‘contacts’],
components: {RouterLink},
template: <ul> <li v-for="contact of contacts"> <RouterLink :to="
/contacts/${contact}"></RouterLink> </li> </ul>
},
Contact: {
props: [‘id’],
template: <div>{{id}}</div>
}
}
}
</script>
### [](#components)Components
## [](#router)`Router`
Router acts as a provider to the various other components, or any other component which is decorated with `withRouter`, passing down the current location, and history object. It expects a location object, which has an API similar to `window.location` and a history object, with an API similar to `window.history` to be passed in as props.
## [](#historyrouter)`HistoryRouter`
A component which passes the browser's history and location (via the `history` module on npm) to Router. This is what you will want to use (in a browser).
## [](#route)`Route`
Take's two props, `path` and `exact`. Path takes an express style route (which is based on [path-to-regexp](/go/?target=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fpath-to-regexp)), and if the browser's location matches that path, it will show the content. The content can either be a a component, or a scopedSlot. They will be passed the router parameters, the path that matched (useful for nesting routes), and the current url (useful for building nested links), either as props, or as parameters, respectively.
Passing in `exact` as true will make the route match exactly.
<Route path=“something/:id”> <template scope="{id, path, url}"> {{id}} {{path}} {{url}} </template> </Route>
## [](#routerlink)`RouterLink`
Takes three props, `to`, `activeClass` (defaults to 'active') and `tag` (defaults to `a`). This will render a link tag which knows how to update the location, and will set an active class when the route matches the link.
## [](#matchfirst)`MatchFirst`
Expects a list of `Routes` as slots, and will render the first one that matches.
## [](#redirect)`Redirect`
Takes a prop `to`, and will cause the browser to redirect to that url
## [](#withrouter)`withRouter`
A HOC which will inject the wrapped function and inject the `router` object, which contains the `history` and `location` objects
## [](#withhandleclick)`withHandleClick`
A HOC that takes a component or tag, and returns a component that handles clicks similar to `RouterLink`. This enables using other components or tags as router links without `
原文链接:https://github.com/blocka/vue-component-router
本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。
转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]