Getting Started With Vue and Vapor

Vue.js provides declarative rendering and a component system to simplify building interactive web apps. In this tutorial, you’ll learn how to add a Vue frontend on top of a Vapor and Swift backend. By Joannis Orlandos.

4.7 (3) · 2 Reviews

Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Submitting Results

With the guess selected, it’s time to shine! Did you guess the title right? Well, if there’s no way to submit your answer, you’ll never know.

So, it’s time to implement a submit button!

Using the techniques previously learned, add the following code at the submit button mark:

<button
  type="button"
  class="btn col-sm-5 btn-primary mt-4"
  @click="() => sendGuess(selected)"
>Send Answer</button>

Now, to implement sendGuess, add the following code in the component definition:

sendGuess(index) {
  // 1
  if(!this.guess) {
    return;
  }

  // 2
  axios.patch(`http://localhost:8081/guess/${this.guess.id}`, {
    // 3
    index: index
  }).then(response => {
    // 4
    this.correct = response.data.correct;

    // 5
    this.totalGuesses += 1;
    if(response.data.correct) {
      this.correctGuesses += 1;
    }

    // 6
    this.guess = undefined;
    this.reloadGuess();
  });
},

Here’ a step-by-step breakdown:

  1. A guard statement returns immediately if the guess is null.
  2. Then a PATCH request submits the user’s choice to the Vapor backend.
  3. Encode the PATCH body with a JSON object. The object has a single key, `index` and you set the value to the guessed index.
  4. If the request was successful, the choice’s correctness is set on the state.
  5. This step updates the total and correct guess counts.
  6. Then this step removes and reloads the choices.

Save the file. If you reload your browser you’ll see the final version of your Vue app!

Where to Go From Here

You can download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

Congrats on completing this tutorial! You learned how to create a basic Vue app and connect that app to a Vapor backend.

As you may have guessed, you’ve only scratched the surface of Vue. Their official documentation provides both a fantastic reference, as well as a solid introduction to the what, how and why of Vue.

If you want to learn more about the backend code used in this tutorial, Server-Side Swift With Vapor is a great place to start. If you want to dive deeper into frontend web development, take a look at the React Framework as well.

Feel free to share your high score in the guessing game, or talk about Vue.js in the discussion below!