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

vol*_*one 3 vue.js vue-router vue-component

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

\n\n

http://localhost:8080/123-todays-bike-ride作为路线中的参数123PostID

\n\n

在我的Post.vue组件中,我有以下代码:

\n\n
<template>\n    <div>\n        <h1>{{Post.PostTitle}}</h1>\n        <p>{{Post.Content}}</p>\n    </div>\n</template>\n\n<script>\n    export default {\n        name: "Post",\n        watch:{\n            \'$route.params.PostID\': function() {\n                    this.getPost(); // does not seem to be triggered?\n                }\n        },\n        computed:\n            {\n                Post() {\n                    return this.$store.getters.getPost\n                }\n            },\n        serverPrefetch() {\n            return this.getPost();  // to do with SSR\n        },\n        mounted() {\n            if (this.Post == null || !this.Post.length) {\n                this.getPost();\n            }\n        },\n        methods: {\n            getPost() {\n                return this.$store.dispatch(\'loadPost\', {PostID: this.$route.params.PostID})\n\n            }\n        }\n    }\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n\n

问题是,即使我从 导航http://localhost:8080/123-todays-bike-ridehttp://localhost:8080/999-swimming,浏览器地址栏中的 URL 会发生变化,但视图的内容Post不会更改 \xe2\x80\x93 ,它仍然与帖子的内容相同123-todays-bike-ride

\n\n

显然该watch: { \'$route.params.PostID\'...位不起作用,但为什么以及如何解决它?

\n

Van*_*anz 5

你可以尝试让它深度观察:

   watch: {
    "$route.params.PostID": {
      handler: function(value) {
        console.log(value);
      },
      deep: true,
      immediate: true,
    },
  },
Run Code Online (Sandbox Code Playgroud)

另一种方法是通过重新渲染组件而不使用watch:

通过添加:key="$route.params.PostID"到 Post 组件,例如:

里面ParentComponent.vue

<template>
    <Post :key="$route.params.PostID" />
</template>
Run Code Online (Sandbox Code Playgroud)