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

问题描述 投票:1回答:1

我想在不需要重新加载页面的情况下检索我添加的新报价。现在我必须刷新页面,然后才能看到数据。我使用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));
}
javascript rest vue.js axios restdb
1个回答
1
投票

你必须添加一个 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);
        });
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.