使用vue-router的beforeRouteUpdate钩子函数来控制是否重新获取API数据。
具体代码示例如下:
export default {
data() {
return {
data: null,
};
},
beforeRouteUpdate(to, from, next) {
// 判断路由查询参数是否有变化
if (to.query.search !== from.query.search) {
// 如果有变化,则重新获取API数据
this.getData(to.query.search)
.then(data => {
this.data = data;
next();
})
.catch(error => {
console.log(error);
next(false);
});
} else {
// 如果没有变化,则直接跳转
next();
}
},
methods: {
getData(search) {
// 调用API获取数据
},
},
};
methods: {
getData(search) {
// 利用axios库调用API获取数据
return axios.get('http://api.example.com/data', {
params: {
search: search,
},
})
.then(response => {
return response.data;
})
.catch(error => {
throw new Error(error);
});
},
},
这样,当路由查询参数更改时,会触发beforeRouteUpdate钩子函数,判断是否需要重新获取API数据,以实现避免重复获取API数据的效果。