所以我有一个组件,它在安装后执行代码,如下所示:
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,
}
}
编辑:添加了 immediate true 选项并删除了 mounted() Hook
关于vue.js - Vue 组件不会在路由 URL 参数更改时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54251233/