使用动态路由:
views/Home.vue:
<template> <div>Home</div> </template>
views/User.js:
<template> <div> 当前用户id:{{id}} </div> </template> <script> export default { data() { return { id: this.$route.params.id } }, created() { console.log('created') } } </script>
router.js:
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) import Home from '@/views/Home' import User from '@/views/User' const routes = [ { path: '/', component: Home }, { path: '/user/:id', component: User } ] const router = new VueRouter({ mode: 'hash', routes }) export default router
App.vue:
<template> <div id="app"> <router-link to='/'>首页</router-link> | <router-link to='/user/1'>用户1</router-link> | <router-link to='/user/2'>用户2</router-link> <router-view></router-view> </div> </template>
效果:
此时,切换用户1或用户2时,路由变了但是页面并没有更新。
原因:当使用动态路由时,从 /user/1 跳转到 /user/2 时,user组件会被复用,这意味着不再走生命周期,所以组件没有更新。
解决办法:
1、watch
2、beforeRouteUpdate
watch: { $route: { handler(newVal) { this.id = newVal.params.id } } }, // beforeRouteUpdate(to, from, next) { // this.id = to.params.id // next() // }
3、直接在模板中使用params的值
<template> <div> 当前用户id:{{$route.params.id}} </div> </template>
4、路由解耦
①路由表中添加 props: true
const routes = [ { path: '/', component: Home }, { path: '/user/:id', component: User, props: true } ]
②User.vue中通过props接收id
<template> <div> 当前用户id:{{id}} </div> </template> <script> export default { props: ['id'], data() { return {} }, created() { console.log('created') } } </script>