观看$ route.params.id不会触发Vue组件的重新渲染

第一卷:

我有一个Post显示用户帖子组件。到达帖子的URL /路由如下:

http://localhost:8080/123-todays-bike-ride123作为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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章