vue如何让请求只触发一次
时间: 2023-04-06 10:01:56 浏览: 81
可以使用Vue的computed属性来实现请求只触发一次。在computed属性中定义一个方法,该方法返回一个Promise对象,然后在模板中使用该computed属性即可。由于computed属性只有在其依赖的数据发生变化时才会重新计算,因此请求只会触发一次。
示例代码如下:
```
<template>
<div>{{ data }}</div>
</template>
<script>
export default {
data() {
return {
isLoading: false,
responseData: null
}
},
computed: {
fetchData() {
if (!this.isLoading && !this.responseData) {
this.isLoading = true
return fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => {
this.isLoading = false
this.responseData = data
})
} else {
return Promise.resolve(this.responseData)
}
},
data() {
return this.fetchData.then(data => data.someProperty)
}
}
}
</script>
```