vue中路由跳转view却不更新的问题与解决办法

一般情况下路由从/myrouter跳转至/yourrouter时,view会发生更新。

1
若遇到/products/:id这样只改变id号的场景。就不会发生更新

情况如下:

router.js

1
2
3
4
5
{
path: "/products/:id",
name: "product",
components: Product
}

现在路由/products/:id对应一个组件Product.vue,组件中有

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div>
<h1>test1</h1>
<p>msg: {{msg}}</p>
</div>
</template>

<script>
mounted(){
this.init(this.$router.history.current.params.id);
},
methods:{
init(id){
this.msg = this.$router.history.current.params.id;
}
}
</script>

为什么上述情况会导致view不更新呢?

1
答:由于router-view是复用的,单纯的改变id号并不会刷新router-view。追根揭底就是因为data没有变化,只要路由跳转时触发 init() 函数来改变data就可以了。

解决办法:

  1. 用 :key 来阻止“复用”

    在父组件中使用

    1
    2
    3
    4
    5
    6
    7
    <router-view :key="key"></router-view>

    computed: {
    key() {
    return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()
    }
    }

    这种办法实质上是让每次路由跳转时重新构建该组件,我们在它的生命周期中写一个打印语句就能看出来。

  1. 通过 watch 监听路由

    在子组件中使用

    1
    2
    3
    4
    5
    watch: { //通过watch来监听路由变化
    '$route': function () {
    this.init(this.$router.history.current.params.id);
    }
    }
  2. 通过 vue-router的钩子函数 beforeRouteEnter beforeRouteUpdate beforeRouteLeave

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当钩子执行前,组件实例还没被创建
    },
    beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    },
    beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    }
× 请我吃糖~
打赏二维码