vue router的使用
时间: 2023-08-23 19:59:11 浏览: 45
Vue中的router-link组件可以用来实现页面跳转,并且可以传递参数。具体步骤如下:
1. 在router/index.js中定义路由:
```
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Detail from '@/components/Detail'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail/:id',
name: 'Detail',
component: Detail
}
]
})
```
2. 在Home组件中使用router-link传递参数:
```
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id">
<router-link :to="{ name: 'Detail', params: { id: item.id } }">{{ item.title }}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, title: '文章1' },
{ id: 2, title: '文章2' },
{ id: 3, title: '文章3' }
]
}
}
}
</script>
```
3. 在Detail组件中获取参数:
```
<template>
<div>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: '',
content: ''
}
},
mounted() {
const id = this.$route.params.id
// 根据id获取文章详情
// ...
this.title = '文章标题'
this.content = '文章内容'
}
}
</script>
```
这样就可以实现通过router-link传递参数并在目标组件中获取参数的功能了。