问题描述
前段时间遇到一个问题 然后查了资料解决了 今天又遇到 忘记了 重新找到以前代码 所以做个笔记:点击文章列表跳转到文章详情, 在列表页跳转路由, 路由携带id 跳转到详情页, 在详情页通过导航守卫获取路由里的id ,获取的id到文章通过访问后端获取数据再渲染具体某篇文章的内容 。
1.文章列表携带文章id跳转路由
//文章列表携带文章id跳转路由
this.$router.push(`/${categoryId}/article`)
2.在文章详情页获取id
created() {
this.articleId = this.$route.params.articleId
// 查询文章信息
getActivityById(this.articleId).then(res => {
console.log(res.data.data)
const result = res.data.data
this.articleDetail =result.activity
this.categoryName = result.category.name//获取类名
})
},
问题分析
点击文章路由跳转 跳转的都是同一个组件,在文章详情页组件中的created中获取id,路由虽然变了 但是加载的是同一个组件 created并不会重新运行,获取到的id一直是第一次加载组件时的那个id
解决办法
为router-view 添加key
<template>
<div id="main">
<router-view :key="key">
<router-view>
</router-view>
</router-view>
</div>
</template>
<script>
export default {
components:{
},
computed: {
key() {
return this.$route.path + Math.random()
}
}
}
</script>