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

2022-03-28 vue.js vue-router vuejs2

所以我有一个组件,一旦它被挂载,它就会执行代码:

    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调用不会更新我的标记。为什么会发生这种情况?

VueJS

原因很简单,即使推荐答案更改了组件,但VueJS基本上是在重用组件,因此不会再次调用mount()方法。

通常,您只需设置一个观察器并对代码进行一点重构

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选项并删除了装载的()挂钩

相关文章