Getting Started with Vue.js – Part 1

Over the past few years, few web frameworks have survived. Vue.js has not only survived but thrived. Let’s see why.

Kshitij Sobti | feedback@digit.in

The world of web development is one of constant churn; new frameworks pop up one day and take the world by storm, only to disappear in a month. If you are looking to create an actual app that is intended to be deployed for people to use, it is important to consider the history of a project and how active its development is at the moment. Vue.js has been around for over three years, and in that time it has gained a lot in popularity for its simplicity, minimalism and performance. It calls itself ‘The Progressive JavaScript Framework’ and markets itself with the keywords Approachable, Versatile and Performant. As you may have derived from the name, Vue.js mostly concerns itself with the View part of your application. It lets you create reusable components that can be composed to build powerful, reactive user interfaces. Like many modern web frameworks, Vue.js uses a virtual DOM to make the framework fast and responsive. It is not concerned with how you connect to your API, how you fetch data. It doesn’t enforce any structure to your code or concern itself with your business logic. It doesn’t even enforce a structure for your Vue.js code. In fact you can create a working Vue.js app in a single JavaScript file that is loaded directly in your HTML page, along with the Vue.js code with no requirement for a build step. Of course, if you want to use the latest JavaScript syntax and want to bundle your code better you will still need something like Webpack. We will use some modern JavaScript features that require a somewhat modern browser. Any recent version on Chrome, Firefox, Safari or Edge will work – Internet Explorer will not. We will be building a simple app that lets you search for users on GitHub using their public API.

SETTING UP OUR CODE
We will set up our Vue app the simple way, without using any external tools. We will simply create an HTML file that includes Vue and our code, and optionally some CSS to make the application presentable. Create a fresh directory to play around in, and in it create an empty HTML file called index.html and a JavaScript file called app.js. Of course you can call these files whatever you want, but you will need to adjust the code examples accordingly. You can paste in any simple boilerplate HTML5 code. All you need in the header section is this script tag that will load Vue from a CDN: And inside the body tag create a single div tag where the app will be mounted, and a script tag to include our app code: If you open this HTML file in the browser and open the console, you should see output like “You are running Vue in development mode.

VUE.JS BASICS
Before we delve into the code, there are a few things you should know about how Vue works. Since Vue is a framework for building user interfaces in a web browser, at some point it needs to output HTML that will be rendered to the page. Different frameworks have different approaches for how this output is generated, and the approach Vue uses is that of templates. You provide Vue some template HTML code that has special markup for where to fill-in data, and Vue will not only fill in the data you provide but also create a binding so any changes to your data will automatically update the relevant parts of the UI. Let’s look at the simplest example of a “Hello World” app here: http://dgit. in/HlwWrld. As you can see in the code example above, we are creating a new Vue instance and providing it a template for our output via template, the data to fill into the template via data and the HTML element in our page – where this Vue component is to be rendered – via el. Setting el to ‘#app’ tells it to mount the component in the element with an id of app; Vue will then render this component and place it where the we put the div with an id of app. The template above is an HTML code with a placeholder for message defined by putting it inside double curly-braces. Vue will look at the value of greeting in data and fill it in the placeholder inside the h1 tag.If you were to now change this value of greeting it would automatically reflect the change in the app. For now you can try this with your browsers console, by setting different values for app.greeting.

TEMPLATES
You’ve already seen how templates can fill in values inside tags, but they can do a lot more. It can fill in attributes like a link’s target location (href), or an image’s source (src). Remember, Vue creates bindings, so when you update any property in data, Vue will also rerender the affected parts of your app with the new values. The curly-brace syntax you’ve seen till now cannot be used for binding to attributes, Vue has a different syntax for that. Here are two examples of how to bind attributes on an image: The v-bind here is what Vue calls a directive, and it sets up a binding between the src attribute and the url property. Since it’s very common to bind attributes to properties, there’s a simpler alternative syntax, simply omit v-bind and keep the colon as you can see with :alt. Bindings needn’t just be to properties, they can be JavaScript expressions like {{ first_name + last_name }}, or :href=”‘/article/’ + id”. Even calling methods inside binding is fair game as long is your method is also defined. For instance:
Author: {{ uppercase(author) }}
This would call the uppercase method, pass it the author and render the result in place. Just like properties are looked up inside data, methods are looked up inside methods. For data transformations like above, Vue has a better syntax called filters: {{ some_string | uppercase | reverse }} This will pass some string through the uppercase method and then pass the result through the reverse method. The above would be equivalent to reverse(uppercase(some_string)) but hopefully you’ll agree the filter syntax is better. The methods used as filter need to be declared inside filters instead of methods. Remember the GitHub User search app we wanted to build? Let’s look at some code from that to learn about loops and conditionals in Vue templates: {{ user.login }} (U) (O)
The v-for directive here will output this list element for each entry in the users array. The current element will be available as user. Often you’ll also need access to the iteration counter, you can get that using (user, index) in users. When looping it’s best to provide a :key binding that’s unique for each instance. The two spans at the end show an if-else block at work in Vue. The v-if directive tells Vue to render the element only if the expression evaluates to true. If there’s also an element with v-else like above, that will be rendered instead in its place. While we haven’t used CSS classes here, Vue provides some convenience features when dealing with them. The class attribute can be bound to a variable just like other attributes, however unlike the actual attribute your variable doesn’t need to be a string. If you provide an object like :class=”{ primary: isPrimary, disabled: !enabled }” and Vue will then apply the primary class if isPrimary is true, and apply the disabled class if enabled is false. You can also provide an array of strings and objects which Vue will combine to make the final class string. With such long templates it’s inconvenient to fit them in a single line. The traditional ways of getting multiline strings in JavaScript aren’t very convenient as they involves adding up single-line strings with + signs or ending each line with ”. What we’ll use for our examples is a new syntax added last year that allows multi-line strings as long as they are quoted using the backtick character ( ` ) (on the left of the number 1 on QWERTY keyboards). There are other approaches available while building real applications. One way is to keep the template used in your HTML code inside a template tag and refer to it using its id. Other, even better methods are available once you involve a build system like Webpack, but we won’t go into that here.

To be continued…..

Leave a Comment

Your email address will not be published. Required fields are marked *