This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging
More details can be found in VueRouter’s official documentation
$router is used to access the entire router.$route is also used to access the current route
// Home.vue export default { computed: $route () {return this.$route.params.username}}, methods: {goBack() {// this.$router access the entire router object window.history.length > 1? this.$router.go(-1) : this.$router.push('/') } } }Copy the code
2. You can set multiple path parameters for a dynamic route, and the corresponding values are all set to $route.params
model | Matching path | $route.params |
---|---|---|
/user/:username | /user/evan | { username: evan } |
/user/:username/post/:post_id | /user/evan/post/123 | { username: 'evan', post_id: '123' } |
3. If path is provided in programmatic navigation, params is ignored
const userId = '123' router.push({ name: 'user', params: { userId }}) // -> /user/123 router.push({ path: ` ` / user / ${username}}) / / - > / user / 123 / / params does not effect the router here. Push ({path: '/ user' params: {username}}) / / - > / userCopy the code
4. When routing parameters change, such as navigating from /user/foo to /user/bar, the original component instance will be reused. To respond to this change, simply watch the $route object:
const User = { template: '... ', watch: {$route(to, from) {// respond to route changes... }}}Copy the code
6. The beforeRouteEnter guard in the component’s navigation guard cannot access this because the guard is called before the navigation is confirmed, so the incoming component has not yet been created. Component instances can be accessed by passing a callback to next. The callback is performed when the navigation is confirmed, and the component instance is taken as a parameter to the callback method.
BeforeRouteEnter (to, from, next) {next(VM => {// access component instance via 'vm'})}Copy the code
7. Complete navigation parsing process
- Navigation is triggered.
- Called in an inactive component
beforeRouteLeave
The guards. - Call global
beforeEach
The guards. - Called in a reused component
beforeRouteUpdate
Guard (+ 2.2). - Called in the routing configuration
beforeEnter
. - Resolve the asynchronous routing component.
- Called in an activated component
beforeRouteEnter
. - Call global
beforeResolve
Guard (+ 2.5). - Navigation is confirmed.
- Call global
afterEach
Hook. - Triggers a DOM update.
- call
beforeRouteEnter
Guard passnext
The created component instance is passed in as an argument to the callback function.