我正在构建一个使用 Stackoverflow’s API 的应用程序 获取特定标签 的last question 并将其输出到我的应用程序。我已经能够在特定标签 上得到最后一个问题,但现在我想要那个 自动检测API 端点 中的更改,并在不刷新浏览器或调用函数的情况下获取发布的最后一个问题。我试过 Computed Properties & Watchers ,但我还没有让它工作。我可能做错了,或者我的解决方案不是正确的方法。
这是我的代码片段:
<template>
<div class="question container-fluid">
<h1 class="my-3"
>
Last "<span class="question_tag">{{ tag }}</span>" Question Details
</h1>
<b-form
class="my-4"
@submit.prevent="updateTag"
>
<b-form-input
class="w-auto"
placeholder="Enter a stackoverflow tag"
type="text"
v-model="newTag"
>
</b-form-input>
</b-form>
<div class="question_title my-2">
<strong>Title: </strong> <span>{{ details.title }}</span>
</div>
<div class="question_status my-2">
<strong>Question answered: </strong><span>{{ details.is_answered }}</span>
</div>
<div class="question_views my-2">
<strong>Views: </strong><span>{{ details.view_count }}</span>
</div>
<div class="question_answers my-2">
<strong>Answers Count: </strong><span>{{ details.answer_count }}</span>
</div>
<div class="question_link my-2">
<strong>Check question: </strong>
<a :href="details.link"
:title="details.link"
rel="noopener"
target="_blank"
>
Here
</a>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'QuestionInfo',
data(){
return {
details: '',
tag: `phaser-framework`,
newTag: ''
}
},
mounted() {
this.getTag()
},
methods: {
getTag(){
axios.get(`https://api.stackexchange.com//2.2/questions?order=desc&sort=creation&tagged=${this.tag}&site=stackoverflow`).then(response => {
this.details = response.data.items[0]
// console.log an error if get() method is unsuccessful
}).catch(err => {
console.log(err)
})
},
updateTag() {
this.tag = this.newTag
this.getTag();
},
},
}
</script>
编辑:
我想找到一个客户端解决方案...最好是 Vue 如果有解决方案。我想尽可能避免使用此功能的服务器端解决方案。
最佳答案
我找到了解决办法。这不是最优雅的,但我最终决定使用 setInterval()
并每 10 秒 进行一次新 API 调用。每10 秒 获取一次新数据不会到达 Stack Exchange API's daily limit & 解决了我的问题。
代码片段:
<script>
import axios from 'axios'
export default {
name: 'QuestionInfo',
data(){
return {
details: [],
tag: `jquery`,
newTag: ''
}
},
// makes an API call on page load
mounted() {
this.getTag()
},
methods: {
getTag(){
setInterval(() => {
axios.get(`https://api.stackexchange.com//2.2/questions?order=desc&sort=creation&tagged=${this.tag}&site=stackoverflow`).then(response => {
this.details = response.data.items[0]
// console.log an error if get() method is unsuccessful
}).catch(err => {
console.log(err)
})
}, 10000);
},
updateTag() {
this.tag = this.newTag
this.getTag();
},
},
}
</script>
关于javascript - 如何使用 Vue 在 API 端点中自动监视更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405711/