vue3 路由切换加载axios
时间: 2023-07-20 12:17:58 浏览: 49
在 Vue3 中,可以通过使用 `beforeRouteEnter` 和 `beforeRouteUpdate` 钩子函数来在路由切换时加载 axios 数据。
1. 在组件中定义需要加载数据的方法:
```js
methods: {
fetchData() {
axios.get('/api/data')
.then(response => {
// 处理数据
})
.catch(error => {
// 处理错误
})
}
}
```
2. 在 `beforeRouteEnter` 钩子函数中调用 `fetchData` 方法:
```js
beforeRouteEnter(to, from, next) {
const component = this
component.fetchData()
.then(() => {
// 数据加载完成后,调用 next() 方法
next()
})
.catch(() => {
// 处理错误
next(false)
})
}
```
3. 在 `beforeRouteUpdate` 钩子函数中判断路由参数是否发生变化,如果变化则重新加载数据:
```js
beforeRouteUpdate(to, from, next) {
const component = this
if (to.params.id !== from.params.id) {
component.fetchData()
.then(() => {
next()
})
.catch(() => {
next(false)
})
} else {
next()
}
}
```
这样,在路由切换时,就可以自动加载数据了。
阅读全文
相关推荐

















