【问题标题】:Watch $route.params.id does not trigger re-render of Vue component观看 $route.params.id 不会触发 Vue 组件的重新渲染
【发布时间】:2020-07-19 19:53:57
【问题描述】:

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

http://localhost:8080/123-todays-bike-ride 123 是路由中的 PostID 参数。

在我的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'... 位不起作用,但为什么以及如何解决它?

【问题讨论】:

    标签: vue.js vue-component vue-router


    【解决方案1】:

    您可以尝试让它深入观看:

       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>
    

    【讨论】:

    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2017-03-14
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多