我有一个Post
显示用户帖子的组件。到达帖子的URL /路由如下:
http://localhost:8080/123-todays-bike-ride
与123
作为PostID
在路由PARAM。
在我的Post.vue
组件中,我有以下代码:
<template>
<div>
<h1>{{Post.PostTitle}}</h1>
<p>{{Post.Content}}</p>
</div>
</template>
<script>
export default {
name: "Post",
watch:{
'$route.params.PostID': function() {
this.getPost(); // does not seem to be triggered?
}
},
computed:
{
Post() {
return this.$store.getters.getPost
}
},
serverPrefetch() {
return this.getPost(); // to do with SSR
},
mounted() {
if (this.Post == null || !this.Post.length) {
this.getPost();
}
},
methods: {
getPost() {
return this.$store.dispatch('loadPost', {PostID: this.$route.params.PostID})
}
}
}
</script>
问题是,即使我从头http://localhost:8080/123-todays-bike-ride
开始导航,http://localhost:8080/999-swimming
浏览器地址栏中的URL也会更改,但Post
视图的内容不会更改–它与123-todays-bike-ride
帖子保持相同的内容。
显然该watch: { '$route.params.PostID'...
位不起作用,但是为什么以及如何解决呢?
您可以尝试使其更深入:
watch: {
"$route.params.PostID": {
handler: function(value) {
console.log(value);
},
deep: true,
immediate: true,
},
},
另一种通过不使用而重新渲染组件来实现此目的的方法 watch:
通过添加:key="$route.params.PostID"
到Post组件,例如:
内 ParentComponent.vue
<template>
<Post :key="$route.params.PostID" />
</template>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句