步骤:1 在路由路径下添加传递的参数:id
2 传递参数 在router-link标签下做参数传递
3 接收参数 $route.param.id
直接看案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>路由传参</title>
<script src="vue.js"></script>
<script src="node_modules/vue-router/dist/vue-router.js"></script>
</head>
<style>
/*li{*/
/* display: inline-block;*/
/* list-style-type: none;*/
/*}*/
.show{
width: 300px;
height: 300px;
background: #cccccc;
}
</style>
<body>
<div id="box">
<ul>
<!-- 通过路由跳转不再是使用a href-->
<li><router-link to="/home">首页</router-link></li>
<li><router-link to="/news">新闻</router-link></li>
<li><router-link to="/hot">热点</router-link></li>
</ul>
<div class="show">
<router-view></router-view>
</div>
<button @click="back" style="background: #cccccc">go back</button>
</div>
<template id="news">
<ul>
<!-- 需要传递的参数-->
<li><router-link to="/news/0">新闻1</router-link></li>
<li><router-link to="/news/1">新闻2</router-link></li>
<li><router-link to="/news/2">新闻3</router-link></li>
</ul>
</template>
<template id="nd">
<div>
<p>新闻详情页</p>
<p>打印出获取到的参数{{$route.params.id}}
{{arr[$route.params.id]}}
</p>
</div>
</template>
<script>
// 定义三个组件
const Home ={template:"<h1>首页</h1>"}
const News ={template:"#news"}
const Hot ={template:"<h1>热点</h1>"}
const NewsDetail={template:"#nd",
data:function () {
return{
arr:["我是第一条新闻的详细信息","我是第二条新闻的详细信息","我是第三条新闻的详细信息"]
}
}
}
// 配置路径信息
const arr=[
{
path:"/home",
component:Home
},
// 进行参数传递
{
path:"/news",
component:News
},
{
path:"/news/:id",
component:NewsDetail
},
{
path:"/hot",
component:Hot
},
]
//创建router实例
const router=new VueRouter({
routes:arr
})
//挂载到Vue
var vm = new Vue({
el:"#box",
router:router,
beforeCreate:function () {
// 通过$router对象去访问地址
this.$router.push("/home")
},
methods:{
back(){
console.log("")
this.$router.go(-1)
}
}
})
</script>
</body>
</html>