实现思路
- 使用 this.$router.push(location) 来修改 url,完成页面路由跳转
- 使用params来隐式传递url的参数,它类似post,url看不出,使用query来传递参数的话,类似get,url一定会被格式化为http://www.xxx.com/index?id=123,而不能自定义,以html后缀结尾
代码示例:
路由部分
{path: '/share/:detailId', // path用这种写法是这个思路实现伪静态的核心name: 'detailLink',component: ArticleDetail
}
列表页面事件跳转部分
checkDetail: async function (articleId, viewCount) {// 阅读量自增await countPageViews(articleId, Number(viewCount))// 伪静态路由跳转this.$router.push({name: 'detailLink', params: {detailId: articleId + '.html'}})}
详情页面
created: function () {console.log(this.$route)let obj = {}obj.article_id = this.$route.params.detailId.slice(0, -5)// 取文章detail数据this.$store.commit('setArticles', obj)},
至此,已基本上实现vue的伪静态需求,理论上可以针对任何页面做伪静态
这里会有一个坑,是这样的,当你同一个路由的时候,只是参数变化了,变化后需要手动刷新,数据才出来,显然是达不到需求的
修复bug,以上面的编码为示例,逻辑都一样
把created里的代码,抽取到method里面,使用vue的watch监测路由变化
created: function () {this.getArticleDATA()
},
methods: {getArticleDATA: function () {let obj = {}obj.article_id = this.$route.params.detailId.slice(0, -5)// 取文章detail数据this.$store.commit('setArticles', obj)}
},
watch: {'$route': 'getArticleDATA'
},