动态路由是指在路由定义时使用参数,使得路由的路径是动态生成的。在Vue Router中,可以使用冒号 : 来定义动态路由参数。这样,当用户访问不同的路径时,路由会根据参数的不同来加载不同的组件或页面。下面是动态路由的实现方法:
定义动态路由:在路由配置中使用冒号 : 来定义动态路由参数。
javascript
// main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './components/Home.vue';
import UserProfile from './components/UserProfile.vue';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/user/:id', component: UserProfile }, // 定义动态路由参数
];
const router = new VueRouter({
routes,
});
new Vue({
router,
render: h => h(App),
}).$mount('#app');
获取动态路由参数:在动态路由的组件中,可以使用 $route.params 来获取动态路由参数。
vue
<!-- UserProfile.vue -->
<template>
<div>
<h1>User Profile</h1>
<p>User ID: {{ $route.params.id }}</p >
</div>
</template>
<script>
export default {
// ...
};
</script>
当用户访问 /user/123 路径时,组件 UserProfile 会根据路由参数中的 id 值来显示对应的用户信息。
响应路由参数的变化:如果动态路由参数在同一个组件中多次使用,并且路由参数发生变化时,需要重新获取数据或更新页面,可以使用 watch 监听路由参数的变化。
vue
<!-- UserProfile.vue -->
<template>
<div>
<h1>User Profile</h1>
<p>User ID: {{ userId }}</p >
</div>
</template>
<script>
export default {
data() {
return {
userId: null,
};
},
watch: {
'$route.params.id'(newId) {
// 路由参数发生变化时,重新获取数据或更新页面
this.userId = newId;
},
},
};
</script>
以上是动态路由的基本用法。使用动态路由可以实现根据不同的参数动态加载不同的内容,适用于需要根据用户或其他条件加载不同数据的场景。