Vue 组件不会在路由 URL 参数更改时更新

Vue component doesn't update on route URL parameter change

所以我有一个组件,它在安装后执行代码,如下所示:

    mounted(){
        axios.get('/markers/' + this.username)
        .then(response => {
            this.markers = response.data.markers
        }).catch((error) => console.log(error));
    }

我得到这样的用户名:

username: this.$route.params.username

但是,如果我更改 URL 参数,用户名不会更新,所以我的 AXIOS 调用不会更新我的标记。为什么会这样?

原因很简单,即使认为 URL 正在更改组件,但 VueJS 基本上是在重用组件,因此不会再次调用 mounted() 方法。

通常你可以只设置一个观察者并重构你的代码

methods: {
    fetchData(userName) {
        axios.get('/markers/' + this.username)
        .then(response => {
            this.markers = response.data.markers
        }).catch((error) => console.log(error));
    }
},
watch: {
    '$route.params': {
        handler(newValue) {
            const { userName } = newValue

            this.fetchData(userName)
        },
        immediate: true,
    }
}

编辑:添加了中间 true 选项并删除了 mounted() 挂钩