VueJS - Instances

Hello there, aspiring web developers! Today, we're going to dive into the wonderful world of Vue.js instances. Don't worry if you're new to programming – I'll guide you through this step-by-step, just like I've done for countless students over my years of teaching. So, grab a cup of coffee (or tea, if that's your thing), and let's get started!

VueJS - Instances

What is a Vue Instance?

Before we jump into the code, let's understand what a Vue instance is. Imagine you're building a house. The Vue instance is like the foundation of that house – it's where everything begins. It's the core that controls your entire Vue application.

Syntax

Creating a Vue instance is pretty straightforward. Here's the basic syntax:

new Vue({
  // options
})

It's that simple! We use the new keyword followed by Vue(), and inside the parentheses, we pass an object with various options. These options are like the blueprints for our house – they tell Vue how we want our application to behave.

Your First Vue Instance

Let's create our first Vue instance together. Don't worry if you don't understand everything right away – we'll break it down piece by piece.

Example 1

<!DOCTYPE html>
<html>
<head>
    <title>My First Vue App</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        {{ message }}
    </div>

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

Output

Hello, Vue!

Now, let's break this down:

  1. We include the Vue.js library in our HTML file.
  2. We create a <div> with an id of "app". This is where our Vue application will live.
  3. Inside the <div>, we use {{ message }}. This is called interpolation – it's how we display data in Vue.
  4. In our <script> tag, we create a new Vue instance.
  5. We use el: '#app' to tell Vue which element it should control (our div with id "app").
  6. In the data object, we define a message property with the value 'Hello, Vue!'.

When Vue sees {{ message }} in our HTML, it replaces it with the value of message from our data. Magic, right?

Data and Methods

Vue instances can have more than just data. They can also have methods – functions that can perform actions or computations.

Example 2

<!DOCTYPE html>
<html>
<head>
    <title>Vue Methods Example</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <p>{{ message }}</p>
        <button v-on:click="reverseMessage">Reverse Message</button>
    </div>

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

Output

Initially, you'll see "Hello, Vue!" and a button. When you click the button, the message will reverse to "!euV ,olleH".

In this example:

  1. We've added a button with v-on:click="reverseMessage". This tells Vue to call the reverseMessage method when the button is clicked.
  2. In our Vue instance, we've added a methods object with a reverseMessage function.
  3. The function splits the message into an array of characters, reverses it, and joins it back into a string.
  4. We use this.message to access and modify the message data property.

Lifecycle Hooks

Vue instances have a lifecycle – they're created, mounted to the DOM, updated, and eventually destroyed. Vue provides hooks that allow you to run code at specific stages of this lifecycle.

Example

<!DOCTYPE html>
<html>
<head>
    <title>Vue Lifecycle Hooks</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <p>{{ message }}</p>
    </div>

    <script>
        var app = new Vue({
            el: '#app',
            data: {
                message: 'Hello, Vue!'
            },
            created: function() {
                console.log('Vue instance created!')
            },
            mounted: function() {
                console.log('Vue instance mounted to the DOM!')
                this.message = 'Welcome to Vue!'
            }
        })
    </script>
</body>
</html>

Output

In the browser, you'll see "Welcome to Vue!". In the console, you'll see two messages:

Vue instance created!
Vue instance mounted to the DOM!

Here's what's happening:

  1. The created hook runs when the Vue instance is created. We're logging a message to the console.
  2. The mounted hook runs when the Vue instance is mounted to the DOM. We're logging another message and changing the message data property.

These hooks are incredibly useful for running code at specific points in your application's lifecycle.

Vue Instance Properties and Methods

Vue instances also come with built-in properties and methods. Let's look at a few:

Example

<!DOCTYPE html>
<html>
<head>
    <title>Vue Instance Properties and Methods</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <p>{{ message }}</p>
        <button v-on:click="updateMessage">Update Message</button>
    </div>

    <script>
        var app = new Vue({
            el: '#app',
            data: {
                message: 'Hello, Vue!'
            },
            methods: {
                updateMessage: function() {
                    this.$data.message = 'Message updated!'
                    console.log(this.$el)
                    this.$nextTick(function() {
                        console.log('DOM updated!')
                    })
                }
            }
        })

        console.log(app.$data)
    </script>
</body>
</html>

In this example:

  1. We use this.$data to access the data object directly.
  2. We use this.$el to log the Vue instance's root DOM element.
  3. We use this.$nextTick to run a function after the DOM has been updated.
  4. Outside the Vue instance, we can access its properties using app.$data.

Here's a table of some commonly used Vue instance properties and methods:

Property/Method Description
$data The data object that the Vue instance is observing
$el The element that the Vue instance is managing
$watch Watch a Vue instance's property for changes
$set Set a property on an object, triggering view updates
$nextTick Defer callback to be executed after the next DOM update cycle

Remember, these are just a few examples. Vue.js has many more features and capabilities that we'll explore in future lessons.

I hope this introduction to Vue instances has been helpful! Remember, learning to code is like learning a new language – it takes time and practice. Don't get discouraged if you don't understand everything right away. Keep experimenting, keep coding, and most importantly, keep having fun! See you in the next lesson!

Credits: Image by storyset