Skip to content

Instantly share code, notes, and snippets.

@pmbanugo
Created July 11, 2018 12:18
Show Gist options
  • Save pmbanugo/d4bd9ff8bcf1b008795f747479acebf6 to your computer and use it in GitHub Desktop.
Save pmbanugo/d4bd9ff8bcf1b008795f747479acebf6 to your computer and use it in GitHub Desktop.
Vue for jQuery developers
Vue.js is a framework for building web applications. It has a reactivity system that allows you to model and manage your application state such that when data changes, it's reflected in the UI, without you having to query the DOM. It's reactivity system makes state management simple and easy. With all the buzz around JS frameworks, you may have read about Vue and want to get into using Vue as a developer familiar withjQuery. Perhaps, you just keep seeing things about Vue appear in your favorite newsletters and you're wondering how you can make the transition to Vue. In this post, I'll show you fundamental components of Vue that you need to know to get started with as a jQuery developer.
# Adding Vue.js to your app
The first thing you do is to add a reference to Vue.js to (In or to?) your project. There are various ways you can do this but I'll focus on using a script reference on the page. So add `<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>` to your page. Once added, you then need to initialise Vue. Create a HTML file with the following content
```html
<html>
<head><script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script></head>
<body>
<div id="app">
</div>
<script>
const app = new Vue({
el: '#app'
})
</script>
</body>
</html>
```
The Vue function receives an **options** object that tells Vue how to setup the application upon initialisation. The `el` property tells it the DOM element that Vue will pick and define its territory. Whatever is within this element will be controlled by Vue.
# Display data
In every application we need to display data. In jQuery it'll be done by calling `$(element).text(data)` or `$(element).html(data)`. With this we need to know how to identify the DOM element. In Vue, this can be achieved using text interpolation. Below is how it can be done in Vue
```html
<div id="app">
{{ message }}
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello jQuery friends'
}
})
</script>
```
Here we added a new property when initialising Vue. The `data` object is added to Vue's **reactivity system**, linking the data and the DOM. Vue's reactivity system is one of its distinct features and it makes state management simple and intuitive. With this reactivity system, whenever the state changes, it is automatically reflected on the page. So, if you update the value of `message` it'll automatically reflect in the page. Add the following code to your script
```javascript
setTimeout(() => (app.message = "Hello Vue devs"), 3000);
```
![vue-reactivity.gif](https://cdn.filestackcontent.com/DeY6Tqz2S2GcKNkKiSBx)
There are times we want to display list of items, maybe in a `<table />` or `<ol />`. In jQuery this would require [joining](https://www.htmlgoodies.com/beyond/css/working_w_tables_using_jquery.html) [strings of text](https://stackoverflow.com/questions/8749236/create-table-with-jquery-append) together which is highly prone to error. In Vue it is much simple because the data and the DOM are linked. The code below shows how you'll do it in Vue for a list of people displayed in a list item
```html
<ol>
<li v-for="person in people">
{{ person.name }} is {{ person.age}} yrs old.
</li>
</ol>
```
```javascript
const app = new Vue({
el: "#app",
data: {
people: [
{ name: "Alice Wonderland", age: 25 },
{ name: "Will Smith", age: 29 }
]
}
});
```
The `v-for` attribute we used is a Vue directive. Vue has so many other directives and they all begin with `v-`, and it applies Vue's reactive behaviour to the DOM, making it change as the data changes.
# Handling events
Another common aspect of web apps is handling events when users interact with your app. The `v-on` directive is used to attach event listeners in Vue. Below is a sample code that listens for when a button is clicked and displays an alert box.
```html
<div id="app">
<button v-on:click="alert">Show Alert</button>
</div>
```
```javascript
const app = new Vue({
el: "#app",
methods: {
alert: function() {
alert("Hello World");
}
}
});
```
The `v-on:click` tells Vue we want to listen for the click event for that button, with `alert` as the event handler for it. Functions which Vue should know about are contained in the `methods` property of the **options object** passed to the Vue function upon initialisation. You can call the function with parameters when attaching it.
```html
<div id="app">
<button v-on:click="alert('Justin')">Show Alert</button>
</div>
```
```javascript
const app = new Vue({
el: "#app",
methods: {
alert: function(msg) {
alert(`Hello ${msg}`);
}
}
});
```
![Screen Shot 2018-07-11 at 07.46.13.png](https://cdn.filestackcontent.com/iXYWWRXzQuaU2Xn4s4oF)
The `v-on` directive has a shorthand, which is `@`. So, if you were to rewrite the snippet which attached a click event handler to the button it'll be `<button @click="alert('Justin')">Show Alert</button>`
# Dealing with forms
Forms are a way to collect information from users. It can contain textbox, checkbox and radio buttons. Vue provides the `v-model` directive which creates a two-way data binding between the application state and the form elements. Let's look at an example
```html
<div id="app">
<form>
Name:
<input v-model="name" placeholder="">
<br />
<br /> Country:
<select v-model="country">
<option disabled value="">Select country</option>
<option>Nigeria</option>
<option>Ghana</option>
<option>Rwanda</option>
</select>
</form>
<p>Name: {{ name }}</p>
<p>Country: {{ country }}</p>
</div>
```
```javascript
const app = new Vue({
el: "#app",
data: {
name: "",
country: ""
}
});
```
![vue--v-model.gif](https://cdn.filestackcontent.com/luDEmv1GTKCq8yvpli9P)
You can see with less code and no direct DOM manupulation you can get the user's input and also display it in a separate paragraph. With this it's easier to collect data and post to a server for storage.
```html
<form @submit.prevent="submitForm">
Name:
<input v-model="name" placeholder="">
<br />
<br /> Country:
<select v-model="country">
<option disabled value="">Select country</option>
<option>Nigeria</option>
<option>Ghana</option>
<option>Rwanda</option>
</select>
</form>
```
```javascript
const app = new Vue({
el: "#app",
data: {
name: "",
country: ""
},
method: {
submitData: function() {
fetch("https://httpbin.org/post", {
method: "POST",
body: JSON.stringify({ name: this.name, country: this.country })
});
}
}
});
```
To collect the data, we listen for the form's submit event using `@submit.prevent`. The `.prevent` is an event modifier which in this case is a shorthand for calling `event.preventDefault()` inside the event handler function. Then to post data you can use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or some other http library (e.g [axios](https://github.com/axios/axios)) to post the data to a server.
# Hiding and showing things
Another common feature is hiding and showing things based on a boolean state value. This can be hiding certain portions of the page based on the user's role or toggling the display of a section of the page by the click of a button. In Vue, you can achieve this using `v-if` and `v-show` directive. Let's look at an example
code
```html
<div id="app">
<button @click="show = !show">
Toggle Panel
</button>
<p v-if="show">Please only call me when I'm needed!</p>
</div>
```
```javascript
const app = new Vue({
el: "#app",
data: {
show: true
}
});
```
![vue-conditional.gif](https://cdn.filestackcontent.com/K1x1pcqQqSMiG8cdAwxd)
With the code above the content of the `<p />` tag is displayed if the `show` state is true. This can also be acieved with `v-show`, but there's a slight difference between the two. With `v-if` the element will be completely unmounted while `v-show` will not but rather toggles the `display` css property
of that element. Accompanying the `v-if` is `v-else` and `v-else-if`, and you can read more about [them](https://vuejs.org/v2/guide/conditional.html.
So far, you may have noticed how with Vue you update your application state without querying the DOM. All DOM manipulation is handled by Vue, and you get to write less code and your application is also easier to reason about. There're a lot more to Vue than I've covered. It has its own [CLI](https://www.npmjs.com/package/vue-cli) for for quickly scaffolding new projects, [Vue router](https://github.com/vuejs/vue-router) for handling routing in Single Page Applications, and a lot more [APIs](https://vuejs.org/v2/api/.
> Peter is a Software Developer, tech writer, and maker of Hamoni Sync. He currently works with Field Intelligence were he helps build logistic and supply chain apps. He also gets involved in design research and customer support for these products. He's also a Contributor to Hoodie and a member of the Offline-First community. You can follow him on [Twitter](https://twitter.com/p_mbanugo) or email p.mbanugo@yahoo.com
@pmbanugo
Copy link
Author

Vue.js is a framework for building web applications. It has a reactivity system that allows you to model and manage your application state such that when data changes, it's reflected in the UI, without you having to query the DOM. Its reactivity system makes state management simple and easy. With all the buzz around JS frameworks, you may have read about Vue and want to get into using Vue as a developer familiar with jQuery. Perhaps, you just keep seeing things about Vue appear in your favorite newsletters and you're wondering how you can make the transition to Vue. In this post, I'll show you some fundamental components of Vue that you need to know to get started with as a jQuery developer.

Adding Vue.js to your app

The first thing you do is to add a reference to Vue.js in your project. There are various ways you can do this but I'll focus on using a script reference. You can add <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> to your page, to reference the Vue library. Once added, you then need to initialise Vue. Create a HTML file with the following content

<html>
    <head><script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script></head>
    <body>
        <div id="app">

        </div>
        <script>
            const app = new Vue({
                el: '#app'
            })
        </script>
    </body>
</html>

The Vue function receives an options object that tells Vue how to set up the application upon initialisation. The el property tells it the DOM element that Vue will pick and define its territory. Whatever is within this element will be controlled by Vue.

Displaying data

In every application, we need to display data. In jQuery it'll be done by calling $(element).text(data) or $(element).html(data). With this, we need to know how to identify the DOM element. In Vue, this can be achieved using text interpolation. Below is how it can be done in Vue

<div id="app">
    {{ message }}
</div>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            message: 'Hello jQuery friends'
        }
    })
</script>

Here we added a new property when initialising Vue. The data object is added to Vue's reactivity system, linking the data and the DOM. Vue's reactivity system is one of its distinct features and it makes state management simple and intuitive. With this reactivity system, whenever the state changes, it is automatically reflected on the page. So, if you update the value of message it'll automatically reflect in the page. Add the following code to your script

setTimeout(() => (app.message = "Hello Vue devs"), 3000);

vue-reactivity.gif

There are times we want to display a list of items, maybe in a <table /> or <ol />. In jQuery, this would require joining strings of text together which is prone to error. In Vue, it is much simpler because the data and the DOM are linked. The code below shows how you'll do it in Vue for a list of people displayed in a list item

<ol>
<li v-for="person in people">
    {{ person.name }} is {{ person.age}} yrs old.
</li>
</ol>
const app = new Vue({
  el: "#app",
  data: {
    people: [
      { name: "Alice Wonderland", age: 25 },
      { name: "Will Smith", age: 29 }
    ]
  }
});

The v-for attribute we used is a Vue directive. Vue has so many other directives and they all begin with v-, and it applies Vue's reactive behaviour to the DOM, making it change as the data changes.

Handling events

Another common aspect of web apps is handling events when users interact with your app. The v-on directive is used to attach event listeners in Vue. Below is a sample code that listens for when a button is clicked and displays an alert box.

<div id="app">
  <button v-on:click="alert">Show Alert</button>
</div>
const app = new Vue({
  el: "#app",
  methods: {
    alert: function() {
      alert("Hello World");
    }
  }
});

The v-on:click tells Vue we want to listen for the click event for that button, with alert as the event handler for it. Functions which Vue should know about are contained in the methods property of the options object passed to the Vue function upon initialisation. You can call the function with parameters when attaching it.

<div id="app">
  <button v-on:click="alert('Justin')">Show Alert</button>
</div>
const app = new Vue({
  el: "#app",
  methods: {
    alert: function(msg) {
      alert(`Hello ${msg}`);
    }
  }
});

Screen Shot 2018-07-11 at 07.46.13.png

The v-on directive has a shorthand, which is @. So, if you were to rewrite the snippet which attached a click event handler to the button it'll be <button @click="alert('Justin')">Show Alert</button>

Dealing with forms

Forms are a way to collect information from users. It can contain textbox, checkbox and radio buttons. Vue provides the v-model directive which creates a two-way data binding between the application state and the form elements. Let's look at an example

<div id="app">
    <form>
        Name:
        <input v-model="name" placeholder="">
        <br />
        <br /> Country:
        <select v-model="country">
            <option disabled value="">Select country</option>
            <option>Nigeria</option>
            <option>Ghana</option>
            <option>Rwanda</option>
        </select>
    </form>

    <p>Name: {{ name }}</p>
    <p>Country: {{ country }}</p>
</div>
const app = new Vue({
  el: "#app",
  data: {
    name: "",
    country: ""
  }
});

vue--v-model.gif

You can see with less code and no direct DOM manipulation you can get the user's input and also display it in a separate paragraph. With this, it's easier to collect data and post to a server for storage. Let's look at an example

<form @submit.prevent="submitForm">
    Name:
    <input v-model="name" placeholder="">
    <br />
    <br /> Country:
    <select v-model="country">
        <option disabled value="">Select country</option>
        <option>Nigeria</option>
        <option>Ghana</option>
        <option>Rwanda</option>
    </select>
</form>
const app = new Vue({
  el: "#app",
  data: {
    name: "",
    country: ""
  },
  method: {
    submitData: function() {
      fetch("https://httpbin.org/post", {
        method: "POST",
        body: JSON.stringify({ name: this.name, country: this.country })
      });
    }
  }
});

To collect the data, we listen for the form's submit event using @submit.prevent. The .prevent is an event modifier which in this case is a shorthand for calling event.preventDefault() inside the event handler function. Then to post data you can use the Fetch API or some other HTTP library (e.g axios) to post the data to a server.

# Hiding and showing things

Another common feature is hiding and showing things based on a boolean state value. This can be hiding certain portions of the page based on the user's role or toggling the display of a section of the page by the click of a button. In Vue, you can achieve this using v-if and v-show directive. Let's look at an example
code

<div id="app">
  <button @click="show = !show">
    Toggle Panel
  </button>
  <p v-if="show">Please only call me when I'm needed!</p>
</div>
const app = new Vue({
  el: "#app",
  data: {
    show: true
  }
});

vue-conditional.gif

With the code above, the content of the <p /> tag is displayed if the show state is true. This can also be achieved with v-show, but there's a slight difference between the two. With v-if the element will be completely unmounted while v-show will not, rather, it toggles the display CSS property
of that element. Accompanying the v-if is v-else and v-else-if, and you can read more about [them](https://vuejs.org/v2/guide/conditional.html.

So far, you may have noticed how with Vue you update your what your users see without querying the DOM. All DOM manipulation is handled by Vue, and you get to write less code and your application is also easier to reason about. There're a lot more to Vue than I've covered. It has its own CLI for quickly scaffolding new projects, Vue router for handling routing in Single Page Applications, and a lot more [APIs](https://vuejs.org/v2/api/.

Peter is a Software Developer, tech writer, and maker of Hamoni Sync. He currently works with Field Intelligence were he helps build logistic and supply chain apps. He also gets involved in design research and customer support for these products. He's also a Contributor to Hoodie and a member of the Offline-First community. You can follow him on Twitter or email p.mbanugo@yahoo.com

@segdeha
Copy link

segdeha commented Jul 12, 2018

Looks good! I left one comment as an annotation just saying that I'm a little surprised Vue is smart enough to reference the correct method when you name something the same as a built-in method.

Nice, gentle introduction to Vue for the jQuery devs amongst us!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment