Vue

In this post you'll learn the fundamental components of Vue.js for developers already familiar with jQuery. Get started faster with this introduction to Vue.

Vue.js, a framework for building web applications, 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. This 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.

In this post, I’ll show you some fundamental components of Vue that you need to know to get started as a jQuery developer.

Adding Vue.js to Your App

The first thing you need to do is 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 the following code to your page to reference the Vue library:

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js">
</script>

Once added, you need to initialize Vue. Create an 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 initialization. The el property tells it the DOM element that Vue will pick and define as 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’s 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 initializing Vue. The data object is added to Vue’s reactivity system, linking the data and the DOM. As mentioned earlier, Vue’s reactivity system is one of its most 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 a lot of other directives and they all begin with v-; this one applies Vue’s reactive behavior 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 Vue should know about are contained in the methods property of the options object passed to the Vue function upon initialization. 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 that 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 a 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 that 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 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 (eg, 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:

<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 here.

So far, you may have noticed how with Vue you update what your users see without querying the DOM. All DOM manipulation is handled by Vue, you get to write less code, and your application is also easier to reason about. There’s a lot more to Vue than I’ve covered, of course – it has its own CLI for quickly scaffolding new projects, Vue router for handling routing in single page applications, and a lot more APIs.



For more info on Vue: Want to learn about creating great user interfaces with Vue? Check out Kendo UI for Vue our complete UI component library that allows you to quickly build high-quality, responsive apps. It includes all the components you’ll need, from grids and charts to schedulers and dials.

You can might also be interested in this related content:


Peter Mbanugo
About the Author

Peter Mbanugo

Peter Mbanugo is a software developer, tech writer, and maker of Hamoni Sync. He currently works with Field Intelligence, where he helps build logistic and supply chain apps. He's also a contributor to Hoodie and a member of the Offline-First community. You can follow him on Twitter.

Related Posts

Comments

Comments are disabled in preview mode.