Posts tagged Learning Vue.JS

An Introduction to Vue.js Components

Components are great for those of us looking to harness the true power of Vue.js. If used correctly we can have clean, reusable code, which is what every developer really wants, right?

What is A Component:

The concept of components is not unique to Vue.js. You can find them referenced in many other javascript frameworks. In fact there is a term for this style of programming called component-based development, which is described as:

… a branch of software engineering that emphasizes the separation of concerns with respect to the wide-ranging functionality available throughout a given software system. It is a reuse-based approach to defining, implementing and composing loosely coupled independent components into systems.

In it’s simplest terms, you can compare components to Lego blocks. These blocks contain smaller pieces of code that handle specific features. If there’s one thing you can take away from this post, it’s that components make your code Readable, Reusable, and Reliable.

The Vue Component

A Vue component is just a Vue instance that is assigned to a custom tag-name and renders content in the template. For example, let’s create a simple component that displays a username.

The first argument in the component function is the tag-name my-user-greeting. When we want to use this component, we just add <my-user-greeting></my-user-greeting> to the template and it will render the code found in the second argument. It’s good practice to give a unique name to your tag. This prevents any tag conflicts from other components or packages installed on your application.

The second argument is the actual object that represents our component. It may look very similar to the object that we pass into the Vue Instance, but the data option is no longer an object but a function. This is because we want the data represented in the component to be specific to said component. We don’t want data that changes in our component to have side-effects changing data in other components.

This object accepts all options and lifecycle hooks that a normal Vue instance would accept, with the exception of el, which is not needed since our main Vue instance is already mounted to an element.

The Template Option:

In the above example you’ll see the template option. This option only accepts a string value, and is the markup for what you intend to render with the component. In our example, we are rendering a simple user greeting wrapped in <p> tags.

This option is pretty limited as we can only use a string. Sure we can pass data properties using text interpolation, but if we wanted to add nested HTML elements, this approach becomes cumbersome. Vue.js allows for single file components which will work great for medium to large projects, and my personal preference, but since this is just an introduction, I’ll save that concept for a future post.

Global vs Local Components:

Many of the applications you build with Vue will span over multiple directories and files. If you build a component with the intention to use it anywhere and everywhere, then defining it once will keep your code clean and easy to refactor.

In the first example, we define our component using Vue.component(), this makes the component available to be used globally throughout your app. Because this component is global, we can add <my-user_greeting></my-user-greeting> to any template in our app and the greeting will be rendered.

As you might expect, a local component is scoped only to the template it is referenced in. Let’s take a look at just one way to define a local component.

In the example we are working directly in a Vue instance and using another available option; components. This accepts an object which can have many components. The key in the object is the tag-name you wish to assign to your component. Then we pass an object which holds the template and data. In this case we just set the object to a variable outside the Vue instance.

Now <my-cmp></my-cmp> is available to be referenced, but only in the template which it is defined in. We could not use this component in other templates because it is out of scope.

Wrapping Up

Components offers us a a way to take complex code and simplify it down into organized, easy to read code. Hopefully this dumbs-down the concept of components. The first time I heard about them I felt slightly anxious and overwhelmed. But coming from a Rails background, they were easy to relate to partials. With a little practice, Vue components will begin to take form within your Vue applications, and you’ll never look back!

Learning Vue.js?
Want to follow along with my learning path? Check here for more posts about Vue!
(Visited 49 times, 1 visits today)

Interacting with the Vue Instance

So you’ve dabbled a bit with Vue.js, and you keep hearing about the Vue Instance. Sure, it allows us to interact with Vue.js on our page, but how?

Initializing The Vue Instance

Whether you add Vue.js using the CDN or the CLI tool, you still need to initialize the Vue instance in some way. By initializing this instance, you are then able to start interacting with Vue.js’ core library.

Clearly there’s not much going on in our instance at the moment. new Vue({}) is just our starting point. Below you’ll find some basic options that the Vue instance accepts.

Common Vue Instance Options

el:

In order for our Vue instance to be accessible in our view, we need to first mount it to an existing DOM element. For single page applications (SPAs) this will likely be the element id  attribute that directly follows the body tag.

It’s important to note that the value for el is a plain string, and we do not need to attach the HTML id symbol, #, to the string. Vue.js already expects this value to be an id.

Vue.js takes this element and it’s containing HTML and regenerates the DOM into a Vue template. Since the generation of the DOM occurs only once when the page loads, the only time el is needed as an option is when we initialize a new Vue instance.

data:

One of the benefits to using a Javascript framework like Vue.js is the ability to to make the DOM reactive, and one of the simplest ways to dynamically render data on your page, is to add a data object to the Vue instance. Below is an example of how you would set up your data properties:

The above example is a basic javascript object which contains three properties: namelocation, and interests.  These data properties are now available to be used within our Vue template generated by the el option.

Take a look at the template example below, we can now bind these data properties to our page using text interpolation; using the mustache syntax {{ }}.

Useful side notes when using data:

  • Vue will convert data properties into getters and setters. This allows the page to be reactive.
  • Once the instance initializes, you can no longer add reactive data to the instance this way. There are other ways to add new data with Vue.js, but not using this method.
  • Vue.js proxies all properties found in the data object, so you can reference properties within the instance using this.location. This is helpful in the following options.

methods:

Methods are event driven functions. Say we have a button on our page, which when clicked, changes our location property to San Fransisco. Our template may look like this:

@click= may look new to you, but it’s Vue.js’ way of saying: “When this element is clicked, run this method”. So changeLocation is the name of our method, and we can now define it within our instance.

As mentioned in the data section, since Vue.js proxies all our data properties, we have them available to use in other areas of our instance. In this case we can use this within the Vue instance and we can then reference our data property location. We reset the value, which will then bind to our template.

An important note is that Vue.js is not smart enough to know if it needs to re-run a method if the data dependencies do not change. If location is already set to “San Fransisco” and your method’s task is to change location to “San Fransisco”, the method will run every time.

computed:

Computed properties work just like methods, however they are cached and only re-computed when a dependency changes. These functions are smart, unlike methods, when it comes to knowing if it needs to run or not when the DOM updates.

Computed functions also don’t need to include the parentheses when called in the template.

An important note with computed functions is that they can only run synchronously. If you want to make asynchronous calls out to an API, you can use methods or the watch option.

watch:

Just as the name suggests, this option accepts properties that align with data properties. When a data property changes, you can add a callback function to run. This function is independent from a method or computed function. For instance, if name changes, we can run other functions.

As mentioned above, watch functions are GREAT for asynchronous calls!

By default watch functions automatically pass a value argument, which is the current value of the data property. You can reference this within your function like so:

Other Useful Vue.js Instance Options:

Below you’ll find a few more helpful options. You can find a longer list of options on the Vue API docs here.

props:

Since this post does not cover components, I wont go into too much detail about props, but this option is an array or object which contains data from a parent component to be used in the child component. As well as the properties being passed, you can specify the data types, validators, and required options.

 

Lifecycle Hook:

In addition to all the options mentioned so far, there are special options that execute during the life of the Vue instance. These hooks fire just as their names suggest so no need to go into individual details. These lifecycle hooks are:

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • deactivated
  • beforeDestroy
  • destroyed
  • errorCaptured

So with those stated, here is just a small example how you might want to use these Vue Instance lifecycle hooks:

Wrapping Up with The Vue Instance:

We’ve only covered the tip of the iceberg when it comes to the Vue instance function and it’s available options. With the introduction of components that list of options grows tenfold! However, Vue.js is such a welcoming framework that you could build simple single page apps with just the options mentioned above!

Learning Vue.js, and want to follow along with my learning path? Check here for more posts about Vue!

(Visited 28 times, 1 visits today)