VueJS - Template: A Beginner's Guide

Hello there, future Vue.js superstar! I'm thrilled to be your guide on this exciting journey into the world of Vue.js templates. As someone who's been teaching computer science for years, I can assure you that Vue.js is one of the most beginner-friendly frameworks out there. So, buckle up and let's dive in!

VueJS - Template

What is a Vue.js Template?

Before we start coding, let's understand what a template is in Vue.js. Think of it as the skeleton of your webpage - it's where you define the structure of your HTML and sprinkle in some Vue.js magic to make it dynamic and interactive.

Basic Structure

Here's a simple Vue.js template:

<div id="app">
  {{ message }}
</div>

In this example, {{ message }} is a special syntax in Vue.js called an "interpolation". It's like a placeholder that Vue.js will replace with actual data.

Let's see it in action:

<div id="app">
  {{ message }}
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello, Vue!'
  }
})
</script>

When you run this code, you'll see "Hello, Vue!" displayed on your page. Magic, right? The {{ message }} in the template is replaced by the value of message in our Vue instance's data.

Directives: Vue's Special Instructions

Now, let's talk about directives. These are special attributes that start with v- and give Vue.js instructions on how to behave. They're like little wizards that cast spells on your HTML!

v-bind: Dynamic Attributes

The v-bind directive is used to dynamically bind an attribute to an expression. It's so common that there's even a shorthand for it: :.

<div id="app">
  <a v-bind:href="url">Click me!</a>
  <!-- Shorthand -->
  <a :href="url">Click me!</a>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    url: 'https://vuejs.org/'
  }
})
</script>

In this example, the href attribute of the <a> tag is dynamically set to the value of url in our Vue instance's data.

v-if, v-else-if, v-else: Conditional Rendering

These directives allow you to conditionally render elements based on the truthiness of the expression.

<div id="app">
  <p v-if="seen">Now you see me</p>
  <p v-else>Now you don't</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    seen: true
  }
})
</script>

Try changing seen to false and watch the magic happen!

v-for: List Rendering

The v-for directive is used to render a list of items based on an array.

<div id="app">
  <ul>
    <li v-for="todo in todos">
      {{ todo.text }}
    </li>
  </ul>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    todos: [
      { text: 'Learn JavaScript' },
      { text: 'Learn Vue' },
      { text: 'Build something awesome' }
    ]
  }
})
</script>

This will render a list of todos. Each <li> element is created for every item in the todos array.

Event Handling with v-on

The v-on directive is used to listen to DOM events and run some JavaScript when they're triggered. It's so useful that it has a shorthand too: @.

<div id="app">
  <p>{{ message }}</p>
  <button v-on:click="reverseMessage">Reverse Message</button>
  <!-- Shorthand -->
  <button @click="reverseMessage">Reverse Message</button>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})
</script>

Click the button and watch your message do a backflip!

Two-Way Binding with v-model

The v-model directive creates a two-way binding on form input elements or components.

<div id="app">
  <input v-model="message">
  <p>The message is: {{ message }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})
</script>

Type in the input field and see the message update in real-time. It's like magic, but better - it's Vue.js!

Computed Properties and Watchers

Computed Properties

Computed properties are like super-powered data properties. They're properties that are computed based on other properties.

<div id="app">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello'
  },
  computed: {
    reversedMessage: function () {
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

The reversedMessage property will always be the reverse of message, and it updates automatically when message changes!

Watchers

Watchers are like vigilant guards for your data. They watch for changes in data and perform actions when those changes occur.

<div id="app">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    question: '',
    answer: 'Questions usually contain a question mark. ;-)'
  },
  watch: {
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: function () {
      if (this.question.indexOf('?') === -1) {
        this.answer = 'Questions usually contain a question mark. ;-)'
        return
      }
      this.answer = 'Thinking...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Error! Could not reach the API. ' + error
        })
    }
  }
})
</script>

In this example, we're watching the question property. When it changes, we update the answer and call a method to fetch a new answer from an API.

Methods Table

Here's a table summarizing the methods we've covered:

Method Description Example
v-bind Dynamically bind attributes <a v-bind:href="url">
v-if Conditional rendering <p v-if="seen">Now you see me</p>
v-for List rendering <li v-for="item in items">{{ item }}</li>
v-on Event handling <button v-on:click="doSomething">
v-model Two-way data binding <input v-model="message">

And there you have it! You've just taken your first steps into the wonderful world of Vue.js templates. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Before you know it, you'll be building amazing Vue.js applications. Happy coding!

Credits: Image by storyset