Bob*_*aru 1 vue.js vue-router vuejs2
所以我有一个组件,它在安装后执行代码,如下所示:
mounted(){
axios.get('/markers/' + this.username)
.then(response => {
this.markers = response.data.markers
}).catch((error) => console.log(error));
}
Run Code Online (Sandbox Code Playgroud)
我得到这样的用户名:
username: this.$route.params.username
Run Code Online (Sandbox Code Playgroud)
但是,如果我更改 URL 参数,用户名不会更新,因此我的 AXIOS 调用不会更新我的标记。为什么会这样?
原因很简单,即使 URL 改变了组件也不是,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,
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加了中间 true 选项并删除了 mount() 钩子
| 归档时间: |
|
| 查看次数: |
3981 次 |
| 最近记录: |