我想使用Vue.js进行实时加载



我想在不需要重新加载页面的情况下检索添加的新报价。现在我必须刷新页面,然后我才能看到数据。我使用restdb.io作为数据库,所以在提出帖子请求后,我如何在不重新加载页面的情况下检索所有数据,你能给我一些建议吗,也许可以尝试其他

发射方法

methods: {
addQuote(e) {
e.preventDefault();
if (this.text.length === 0) {
alert("Поле пустое. Пожалуйста введите цитату");
return;
}
const newQuote = this.text;
this.$emit("add-quote", newQuote);
this.text = "";
}
}

POST请求

addQuote(quote) {
if (this.quotes.length === 10) {
alert("Для добавления новых цитат удалите одну из добавленных");
return;
}
axios
.post(
"https://beeline-3fee.restdb.io/rest/db?apikey=<api_key>",
{ text: quote }
)
.then(response => response.data)
.then(quote => {
console.log("Success:", quote);
})
.catch(error => {
console.error("Error:", error);
});
}
}

GET请求

mounted() {
axios
.get(
"https://beeline-3fee.restdb.io/rest/db?apikey=<api_key>"
)
.then(response => (this.quotes = response.data))
.catch(err => console.log(err));
}

您必须添加一个getQuotes方法,并使用它来加载mounted中的报价,并在添加新报价后获取所有报价

mounted() {
this.getQuotes();
},
methods: {
getQuotes() {
axios.get("https://beeline-3fee.restdb.io/rest/db?apikey=5eaaf516161b39295cdee783")
.then((response) => (this.quotes = response.data))
.catch((err) => console.log(err));
},
addQuote(quote) {
if (this.quotes.length === 10) {
alert("Для добавления новых цитат удалите одну из добавленных");
return;
}
axios
.post("https://beeline-3fee.restdb.io/rest/db?apikey=5eaaf516161b39295cdee783",
{
text: quote,
}
)
.then((quote) => {
console.log("Success:", quote);
// this will fetch the quotes again
this.getQuotes();
})
.catch((error) => {
console.error("Error:", error);
});
}
}

最新更新