1、新建带有router的vue项目,在views下添加NewsView.vue页面
<template>
<div>
<ul>
<li>
<router-link to="/newsdetails/百度">百度新闻</router-link>
</li>
<li>
<router-link to="/newsdetails/腾讯">腾讯新闻</router-link>
</li>
<li>
<router-link to="/newsdetails/网易">网易新闻</router-link>
</li>
</ul>
</div>NewsView
</template>
2、在views下添加NewsDetailsView.vue页面
<template>
<p> {{ $route.params.name }}详情 </p>
</template>
3、在router的index.js中配置路由
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// 一般非首页会用这种方式进行引入,这种方式只有要显示时才会加载,相当于加快了网站首页的显示
component: () => import('../views/AboutView.vue')
},
{
path: '/news',
name: 'news',
// 一般非首页会用这种方式进行引入,这种方式只有要显示时才会加载,相当于加快了网站首页的显示
component: () => import('../views/NewsView')
},
{
path: '/newsdetails/:name',
name: 'newsdetails',
// 一般非首页会用这种方式进行引入,这种方式只有要显示时才会加载,相当于加快了网站首页的显示
component: () => import('../views/NewsDetailsView')
},
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
4、app.vue添加新闻
<template>
<nav>
<router-link to="/">首页</router-link> |
<router-link to="/about">关于</router-link> |
<router-link to="/news">新闻</router-link>
</nav>
<router-view/>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>
5、查看效果
新闻界面:
点击百度新闻,跳转到详情界面: