vue中动态路由具体代码
时间: 2023-09-28 20:07:43 浏览: 39
在Vue中,动态路由的具体代码实现如下:
1. 在路由配置文件中定义动态路由:
```javascript
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Product from '@/views/Product.vue'
import ProductDetail from '@/views/ProductDetail.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/product',
name: 'product',
component: Product
},
{
path: '/product/:id',
name: 'productDetail',
component: ProductDetail
}
]
})
```
2. 在组件中使用动态路由:
```html
<template>
<div>
<h2>Product Detail</h2>
<p>ID: {{ id }}</p>
</div>
</template>
<script>
export default {
name: 'ProductDetail',
props: ['id']
}
</script>
```
```javascript
import ProductDetail from '@/views/ProductDetail.vue'
export default {
name: 'Product',
data() {
return {
products: [
{ id: 1, name: 'Product 1' },
{ id: 2, name: 'Product 2' },
{ id: 3, name: 'Product 3' }
]
}
},
components: {
ProductDetail
}
}
```
3. 在路由跳转时传递参数:
```html
<router-link :to="{ name: 'productDetail', params: { id: product.id } }">{{ product.name }}</router-link>
```
```javascript
this.$router.push({ name: 'productDetail', params: { id: productId } })
```
以上就是Vue中动态路由的具体代码实现。