Vue: 通过 vue 的 router 传递参数两种方式总结
通过 vue 的 router 传递参数,通俗说法例如:通过id进行页面跳转并获取数据的方法总结
(一)命名路由传参,即使用params
形式如下:
this.$router.push({ name: 'editor', params: { id: 1 }})
这种方法的name是指路由中定义的那个name,而不是页面路径。跳转到的页面路由不会包含任何参数信息。刷新后就会丢失。
(二)查询传参
形式如下:
this.$router.push({ path: 'jotter/article', query: { id: 1 }});
结合超链接,即可实现点击标题或摘要传递参数到文章详情页面并跳转功能,只要在详情页面获取到该参数并向数据库发送请求即可。获取参数的形式如下
this.$route.query.id
用两种方法实现第二种方法
1、第一种方法
(1)第一步:配置路由:
在router文件夹得index.js配置路由
{
path: '/notices/detail/:id',
// redirect: {
// name: 'ProductIndex',
// },
name: 'Notice',
// component: ProductIndex,
component:() => import ('@/components/home/NoticeDetail'),
meta: {
requireAuth: true
}
},
(2)第二步:在Notice.vue页面写链接跳转实现跳转
完整链接跳转如下:
<ul class="notice-list-ul">
<li
v-for="notice in notices"
:key="notice.id"
>
<router-link :to="'notices/detail/'+ notice.id">
<i class="header-icon el-icon-info" >{{ notice.name }} </i>
</router-link>
</li>
</ul>
下面得代码从上面摘取而来,只是用来说明重点
形式如下:
<router-link :to="'notices/detail/'+ notice.id">
<i class="header-icon el-icon-info" >{{ notice.name }} </i>
</router-link>
(3)第三步:跳转页面根据id获取数据
1)获取id
data() {
return {
id:parseInt(this.$route.params.id),
notice: {},
};
},
2)钩子函数
mounted(){
this.getNoticeDetail()
},
3)获取数据
methods:{
getNoticeDetail(id){
var _this = this
var url = 'notices/detail/' + this.id
this.$axios.get(url).then (resp => {
if(resp && resp.status === 200){
_this.notice = resp.data
console.log(_this.notice )
}
})
}
}
2、第二种方法:
(1)配置路由:
{
path: '/teas/detail/',
name: 'ProductIndex',
component:() => import ('@/components/home/ProductIndex'),
meta: {
requireAuth: true
}
},
(2)第二步:在Product.vue页面写链接跳转实现跳转
链接跳转如下
<router-link :to="{path:'/teas/detail',query:{id:tea.id}}">
<div class="product-title">
<a href="">{{ tea.name }}</a>
</div>
(3)第三步:跳转页面根据id获取数据
1)钩子函数
mounted(){
this.loadOneProduct()
},
2)获取数据
loadOneProduct(){
var _this = this
var url = '/teas/detail/' + this.$route.query.id
this.$axios.get(url).then(resp => {
if(resp && resp.status === 200){
_this.products = resp.data;
console.log(_this.products)
}
})
},