vue实现按需调用接口
Vue 实现按需调用接口的方法
使用计算属性触发接口调用
计算属性基于响应式依赖进行缓存,适合在特定数据变化时触发接口请求。例如,当搜索关键词变化时自动调用搜索接口:
export default {
data() {
return {
keyword: ''
}
},
computed: {
searchResults() {
if (this.keyword) {
return this.fetchSearchResults(this.keyword)
}
return []
}
},
methods: {
async fetchSearchResults(keyword) {
const res = await axios.get('/api/search', { params: { keyword } })
return res.data
}
}
}
监听路由变化触发接口
在组件内监听路由参数变化,实现进入页面或路由参数变更时按需加载:

export default {
watch: {
'$route.params.id': {
immediate: true,
handler(newId) {
if (newId) {
this.fetchDetail(newId)
}
}
}
},
methods: {
async fetchDetail(id) {
const res = await axios.get(`/api/detail/${id}`)
this.data = res.data
}
}
}
手动触发式调用
通过用户交互(如按钮点击)显式触发接口请求,避免不必要的预加载:
<template>
<button @click="loadData">加载数据</button>
</template>
<script>
export default {
methods: {
async loadData() {
const res = await axios.get('/api/data')
this.data = res.data
}
}
}
</script>
条件式懒加载
结合 v-if 指令实现组件挂载时自动请求,适用于需要立即显示但可能被隐藏的数据:

<template>
<div v-if="isVisible">
{{ data }}
</div>
</template>
<script>
export default {
props: ['isVisible'],
data() {
return { data: null }
},
watch: {
isVisible(newVal) {
if (newVal && !this.data) {
this.fetchData()
}
}
},
methods: {
async fetchData() {
const res = await axios.get('/api/data')
this.data = res.data
}
}
}
</script>
优化技巧
防抖处理高频触发
对频繁触发的事件(如输入搜索)添加防抖,避免短时间内重复请求:
import { debounce } from 'lodash'
export default {
methods: {
search: debounce(async function(keyword) {
const res = await axios.get('/api/search', { params: { keyword } })
this.results = res.data
}, 500)
}
}
取消重复请求
使用 Axios 的 CancelToken 中止未完成的相同请求:
let cancelToken
export default {
methods: {
async fetchData() {
if (cancelToken) {
cancelToken.cancel('取消重复请求')
}
cancelToken = axios.CancelToken.source()
try {
const res = await axios.get('/api/data', {
cancelToken: cancelToken.token
})
this.data = res.data
} catch (err) {
if (!axios.isCancel(err)) {
console.error(err)
}
}
}
}
}






