What Is Vuex, And What Is It Used For In VueJS? – A Very Simple Crash Course Tutorial

In jQuery, triggered events were the most important things.

Almost everything that happened, would happen on an onclick, a hover, a keyup/keydown, or some other kind of event.

In Vue, while events sometimes act as triggers in and of themselves, for the most part, the actions that happen within a VueJS UI primarily are triggered by the data within a Vue application, and the changes within that data.

We lay this out in much more detail in our post on VueJS Components, but we will go over how this all works briefly below, as a refresher.

VueJS Data And Components – How It All Works

Vue applications, can be thought of as a collection of cascading, UI based, mini-apps. Those mini-apps, coming in the form of relatively self-contained Vue Components.

These mini-apps or components, are all children of the main parent component that initializes all of the others.

This is usually contained within your App.vue file in your Vue application folder directory.

This is a simple diagram that shows you visually what we are talking about here:

[Add a visual diagram here.]

How Data Works, And Flows Within The VueJS Code Structure

In jQuery, data is typically held across the application without much of a predefined structure. It is usually captured by querying an element ID or class and is pretty much globally accessible across the application by default.

In Vue, data is much more self-contained, yet powerful when used.

With a basic Vue application that does not use components, events will have more of the emphasis, as at this point the Vue application is closer to a jQuery application in terms of general, mostly event-driven flow.

As the VueJS application’s complexity increases and components are added, the data-driven aspects of Vue gradually begin to take hold. Simply meaning that as you create a more complex application with Vue, the level of influence that data has within it, rather than events, increases.

Vue data expresses itself most effectively with Components.

The key to this expression comes down to how well the data moves around the application via the use of components.

As the most efficient unit of the UI. Components allow data to flow seamlessly downwards and upwards from parent component to child component.

An example of this will be shown below as you read on.

But what happens when that component of the UI needs to communicate with another, similar component unit?

Then it gets quite complicated.

But before we get into that, let’s first get into how data typically flows up and down Vue Components.

Then we will discuss how data can flow even more efficiently, in any direction you want, whether that is between components or as we have stated above, up and down them.

This increased efficiency will be had with the use of a tool called Vuex.

How VueJS Components Typically Communicate With One Another, Without Vuex

The simplest, standard method of communication across Vue components is between Parent and Child components, communication also occurs between components more directly. We will explore the ways in which components may communicate below.

Vue.js allows component communication in the following ways:-


1. Parent to child communication (Using Props).

This communication is done downwards via the use of ‘props’ which are simply variables that are specific to a particular parent component, and can be inherited by child components.

These are passed into the child Component via the use of Component arguments as well as set within the parent Component instance itself.

We do this setting of the prop within the parent Component instance like this:

[code showing the setting of a prop within the parent component instance]

We may then pass our prop into our child Component with the use of component arguments like this:

[code showing the passing of a prop within the child component instance]

This is how we pass data from our parent Vue Component down to our child Components.


2. Child to parent communication (Using Events).

To pass on data to our child Components, we use a slightly different strategy. Because we are not able to pass props from our child Components up to our parent (props can only be used by the parent component or be inherited by the child).

To get our data up in the other direction towards our parent component, we use events.

The easiest way of doing this is via the use of Vue’s custom $emit event method.

This method can be used from within the child component like so:

[Example of an $emit event being triggered].

It can then be received by the parent Component like this:

[Example of a parent component receiving the child component data via the use of an event]


3. Communication between any component (Using Event Bus).

While the above two methods work well for communication between parent and child components, up and down, if you want to communicate across components you will simply use the Vue ‘event bus’.

The event bus is basically a global event handler and tracker. It keeps tracks of events in a manner that allows any Vue Component to listen and capture them.

To add an event to the event bus, you must simply emit an event from one component and then listen for the corresponding event within the other component:

[code showing addition of an event to the event bus]

Whenever this event is triggered, you may listen to it within any component you want to. Passing in any relevant data along with it.

To listen to an event within a chosen component, you will simply do y:

[code showing the listening of an event]

This method of doing things is ok, but ultimately, firing events all the time just to pass data from component to component is a bit cumbersome.

This becomes especially true when dealing with a relatively large application.

It would be a lot better if there was some sort of global ‘model’ that we could leverage in order to both add or set data, as well as get it whenever we needed it.

Fortunately, this is what Vuex allows us to do.

How Vuex Works Within the Context Of A Vue App

Note: Before jumping into this part, you will have to load Vuex within your application. You may do this via the command line by typing npm install vuex --save from within your project directory.

Within the context of a Vue app, you will use Vuex by first creating a file within which to house your Vuex Store. A “store” is basically a container that holds your application state.

State is basically an object within which the data that is to be used by the components in your application will be held. Those objects essentially being props that are globally accessible for the Vue application to use.

State is an interesting term, because it basically alludes to the data-driven nature of Vue. An application’s functional ‘state’ is defined by the ‘state’ of its data.

The Vue store works in a similar way to a Vue Instance, in that to set it up, and the structure that it uses to work are very similar.

Once this is done, you will simply reference Vuex within your store.js file like this:

[code showing the referencing of the Vuex files, within the store.js file here]

We will here instantiate our Vuex store within the same store.js file like this:

[code showing us instantiating our Vuex store and then adding the state props that we would like to add].

Vuex essentially allows us to store, mutate (manipulate) and then retrieve our data easily and simply via a globally (by all components) accessible store.

The structure here is very simple. At the top of the store we have the actual ‘state’ data. Under that we have our mutations (methods we use to modify our data).

The data that we’ve set within this object can now be accessed by any of our Vue components.

All we have to do is add our ‘store’ option within our root Vue instance. This allows the stored Vuex data to be accessible by all of our components.

There are many things you can do and many ways that you can now play with this data. From manipulating it with mutations to allowing it to be dynamically accessible via the use of ‘getters’.

The key things that Vuex gives you are easy, safe access to global data as well as a bunch of plugins that supercharge what you can do with that data.

This gives you the ability to deal with application data at a higher level of abstraction, and ultimately, makes the development process just that little bit easier.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below


What Are Vue Components? A Simple, Crash Course Tutorial

Before you can truly begin to understand Vue Components, you must first understand the Vue Instance. Which is just a JavaScript object that attaches itself to a section of your HTML page, and that initiates the Vue functionality and allows it to run through that section of the page.

In the days when jQuery was most popular, the best way to give a webpage some dynamism was to simply overtake the page with moderate functionality. document.ready function anyone? And then once that was done, to simply bind and then interact with any areas of the page that you needed to. 

The problem with this method is as the web’s complexity has increased, and therefore needed more complexity in terms of UI, tools like jQuery, which typically dealth with various sections of the page at once, sometimes with various sections sharing functionality, were now ending up a spaghettified mess. This because there was no modularization and clear seperation of concerns. 

Modules prevent spaghetti code.

VueJS and ultimately, Vue Components are a modularization of the previous method of adding interactivity to a webpage. It allows you to target just the segment of the page you need, therefore being able to concentrate more complexity in terms of functionality within that specific area. Ultimately building up a collection of powerful sections that together create a powerful, performant webpage.

Vue Components are simply Vue Instances that you can name and single out specifically, in order to be able to use them in a more modular, flexible fashion. Basically, Vue Components are Vue Instances that you can move around and/or reuse within your UI. Wherever you may need them to be.

They are, if thought of in another way, simply reuseable abstractions of Vue Instances.

Why Vue Components Are Needed

Increasing webpage complexity has over time been met by increasing functionality, as well as modularity, in order to manage that complexity. This means that section by section, the webpage has been made to handle as well to do, more for the user over time. These sections of the page have gradually evolved to become full blown UI modules with the help of JavaScript. With each module within a webpage having more individual power, in order to gradually together increase the power of the entire webpage.

Said another way, webpages have become a bundle of mini-apps. Each section of the page representing not just a paragraph section or a bunch of images, but now representing a complete, modularized mini-application in its own right. In Vue, these are our modularized Vue Instances, or as we’ve named them above, our Vue Components.

Vue Components are a style of creating one of these mini-apps on your page. They are the mini apps that VueJS has developed for us to use.

How Vue Components Work Within The Context Of A Webpage, And A VueJS App

Since Vue Components are simply modularized, abstracted Vue Instances,  let’s first start with a Vue Instance and and then build our understanding of Components from there. 

A Basic Vue Instance On A Webpage

<div id='app'>{{ someText }}</div>

new Vue({
el: '#app'
      data: {
          someText: 'helloThereText'
      }
})

Things on the web tend to cascade into other things. A ‘web’ as a thing in and of itself is a sort of inverse cascade. So in the same vein, the technologies on this sort of structure will inevitably operate in the same way.

With all technologies used on the web, there is always a root source, or a root initiator. Just like with a spider web, there is a root point where the web began to grow. 

VueJS is no different. 

When we create our Vue applications, no matter how big or complex they become, the root Vue instance will always be our starting point and where everything in our app, including our Vue components, runs through. 

So with this in mind, we will now create our Vue Component.

Creating a Vue Component 

Creating a component in Vue is as simple as registering it within Vue and then within your root instance. There are, infact 4 different ways of creating a Vue Component, which are mentioned in the previous link. 

But for the purposes of this article, and for simplicity, we will only be covering what we believe is the simplest way. That is to register a Vue Component with a template inside of it. 

The way we do this can be seen below:

<div id="app"></div>

const
HWComponent = { template: `<h1>helloThereText</h1>`, } new Vue({ el: '#app', template: ` <div> <HWComponent/> </div> `, components: { HWComponent }, });

Here you can see, we’ve simply replaced our data object with a ‘template’ declaration, where we specify the structure within which our component should be held. 

Below that we specify our component. Or components, depending on how many we would like to use.

The registered component, defined in our above const ‘HWComponent’, is now holding our data, the text that is to be displayed.

For most complex Vue apps and projects, the structure as well as the usage of components, is usually within the context of many other components. All of these being routed through a root App.vue component. Which is then also routed through the final, non-component root Vue Instance.

The creation and management of these more complex Vue apps is done via tools like the Vue CLI. You can learn more about that and of how components are usually used within the context of a real world project here: What Is The Vue CLI – A Mini Crash Course Guide.

For now, this short crash course guide should give you a decent enough glimpse of what exactly Vue Components actually are. And how to create them.

From this foundation, you can hopefully go on and continue to build your knowledge base with regard to Vue Compenents, and, to VueJS as a Framework overall.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below


What Is The Vue CLI – A Mini Crash Course Guide

As you progress in your level of knowledge with VueJS, you will gradually begin to require more and more horsepower with regard to the tooling that you need in order to get your project set up and running.

For most people who learn VueJS, the path to getting setup typically begins by simply loading in the VueJS library that you need via a CDN in script tags.

After you have started to get the hang of what you can do with Vue and are starting to both understand and need to use the more powerful features that it comes with, such as Vue components (link to a post here about Vue components) and the Vue router, you will begin to see that the amount of setup needed to get up and running is much more than you’d probably like to do with the standard, non-Vue specific method. That being the simple addition of a script tag src, as mentioned above.

This is when you’ll probably start to look into tools like the Vue CLI. A command-line utility that makes the setting up of a Vue project, complete with all the functionality that you need to create a complex modern application as easy as a simple command-line statement:

vue create my-project

Why the Vue CLI is necessary for most Vue projects

Just as construction within human civilization evolved in terms of housing, with more and more complexity being solved by various forms of scaffolding, so in the same vein, as the web evolves, various forms of scaffolding are now needed and being made in order to make the web-based application building process easier.

Compared to jQuery, increasing complexity on the web as time has progressed, as well as what that complexity has necessitated, means that much more is needed in terms of scaffolding, to meet the users’ performance demands.

A highly complex web needs an equally complex response in terms of tooling for web builders.

This is what tools like the command-line utility that is the Vue CLI do for you.

The Vue CLI makes the building of complex coding infrastructures that can manage the new complexity that is now on the web, easier.

Complexity meets complexity, but with a tool like the Vue CLI, that complexity is now simplified for the user.

How To Use The Vue CLI – Step By Step

Before you can get to creating your Vue CLI initiated app, you must first install the Vue CLI from npm.

You do this by typing the following npm command into your terminal:

npm install -g @vue/cli

You may also install it with yarn, if you have that package manager installed, like so:

yarn global add @vue/cli

Once you’ve done this, you may now create your Vue project by typing in the following command:

vue create hello-world

We’ve used ‘hello-world’ here as our project name but you may choose any other name that you like.

That’s all there is to it. You now have installed a complete Vue project.

But what does that mean in terms of what we can now do?

How A Vue CLI initiated App Works, And What It Allows You To Do

Once you’ve installed your Vue project, you’re now probably wondering how it works in terms of the folder structure and what everything in it does.

There are only a few key areas that we will focus on in this tutorial, as this is simply a mini crash course.

These are the main areas that interact within the app, and the ones that you’ll need to focus on most of the time when you’re in the process of development.

The understanding of how these areas within the app work will also allow you to further gain a grounding in Vue.

Before we begin to get into what these key areas are, and the ways in which these key areas work, let’s first take a little look at the overall folder structure in the app we’ve just created.

hello-world’ Vue App Folder Structure, The Most Important Parts

The below section are normally within your’src’ folder, inside of your Vue app. This is where your real Vue app lives. And whose contents we will be covering below. In the root directory before you get into src simply is your basic dependency files, such as your ‘node modules’. These are the various key scaffolding elements that are available within your Vue CLI initiated Vue app.

Below, we will simply focus on our Vue app src folder.

[Picture of the Vue App Src folder]

Components

The most important folder to notice here is the ‘components’ folder. This folder holds your Vue components, which are basically self-contained full mini-Vue apps within your overall Vue Application that basically represent a segment of your page. They contain the HTML, CSS, and JavaScript (most of it your Vue code) that you need in order for your Vue functionality to work.

Main.js – The Command Center of Your Vue App

The main.js is the main startup area of your Vue app, where data and processes are routed, it’s here where the main Vue instance is initiated and set ready to go. In most tutorials and by most programmers, you will see a file like this being referred to as your ‘entry’ file, for this reason. This is also where the components that we mentioned previously are connected to the instantiated Vue instance.

App.vue

[picture of App.vue file here.]

App.vue is where we add in and combine the references to all of our app components, as is seen above. We simply add the component element tag name within our main App.vue element and then reference that as one of our instantiated components in our Component’s JavaScript below, within the same file.

This is the file that we then reference within our main.js entry file, in order to load all of our components up.

Assets

We keep our assets such as image files and logos here. For easier referencing from within our app.

On Module Bundlers in the Vue CLI, The Middle Man Of Your App

We mentioned module bundlers above as a standard part of the Vue app creation and running process.

The basic description of a module bundler is as a middle man within your app, that converts the app’s code, which when you’re writing it is not recognizable by the browser that will be running it, down into something that the browser can then run and understand.

The bundling process works by typing in a bundling command on the command line from within your app directory. Like this:

npm run build

This will load the compiled, browser readable files into a /dist folder that can then be used to display your app.

Our /dist folder is where our compiled HTML, js, and CSS is kept once our Vue code has been run through our module bundlers.

All of the above works in order to make your Vue app runnable by most good, modern web browsers.

All of this functionality and the way that it works is available out of the box in the Vue CLI. Once you begin to use the functionality provided, such as the core functionality described above, you will begin to understand the full power of the scaffolding provided by the Vue CLI.

The final feature we will mention in this point, just to show how useful it is, is the Vue CLI serve command.

Like this:

npm run serve

When this is run from within your Vue app directory, it will load up a simple web server and allow you to see your Vue app in action. A link to it on your localhost, along with the relevant port that is running it, will be available on the command line.

Pretty great right?

I hope this gives you a good general overview of what the Vue CLI can do for you. When you start to use it, you will gradually begin to see what it can help you do.

So don’t wait around. Get active with it today, and see just how powerful a scaffolding tool the Vue CLI is.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below


Why Most Programming Tutorials Are So Hard To Understand – (And A Solution To This Problem)

To reason logically is so to link one’s propositions that each should contain the reason for the one succeeding it, and should itself be demonstrated by the one preceding it.

Jean Piaget

The above quote is from the Swiss psychologist Jean Piaget, a well-known figure in not just the psychological field, but also in the education field.

I want you, as you read through this post, to keep this quote in mind.

You will see why as you continue to read.

You might be asking yourself what the above quote might have to do with programming tutorials, and the answer is, well, a lot actually.

But before we can get to fleshing that out, we must first start with the core issue that I believe is the cause of hard to understand programming tutorials (and programming documentation for that matter).

That issue is one of ‘imposter syndrome’.

The Two Sides of the Imposter Syndrome Coin

I have a theory about imposter syndrome. That is that it is simply a symptom of a more profound problem.

That is the problem of believing that everyone is at the same level of knowledge that you are, and that they understand that knowledge in the same way that you do.

In the same way that the self-consciousness that seems to be produced by a lack of ego in, say, a social situation, is actually the result of a preoccupation of the self. Imposter syndrome is likely caused by too much of a focus on one’s own level of knowledge and a mistaken projection of that level out into the social world.

Jean Piaget also seemed to know this well:

Egocentrism is, in its essence, an inability to differentiate between the ego and the social environment.

Jean Piaget, The Moral Judgement of the Child

Egocentrism sounds like a bad thing, a character flaw almost. But it is in fact, simply a description of a very normal human trait. It is, at least according to psychologists like Piaget, how we began to think as children.

It is from this basis that, he believed, we began to gradually differentiate, or said another way, to ‘learn’ our environment, by a gradual process of both separating what was in front of us from ourselves, and then also, combining those things with other things and seeing how they would link and interact.

In this process, he believed, we would gradually ‘build’ knowledge structures from the ground up. These structures would be the representations of the things we were seeing as well as the links between those things, a schema of sorts, of all the things that we had, over time ‘learned’ and connected within the web of our knowledge structure. This with all preceding knowledge serving as the foundation for all the knowledge that would succeed it.

Sound familiar?

This method of learning proposed by Piaget is what became known as the constructivist theory of knowledge.

Jean Piaget’s development of the constructivist theory of knowledge was probably a direct response/result of his discovery that we (including people who teach) have a natural inclination to believe that our own level of knowledge is also the level of other people. A form of ego-centrism that is inherent within all of us. The constructivist theory of knowledge says, in contrast to this, that we should be more empathetic. It encourages us to first endeavor to exercise empathy with our potential student, to try to know what the learner already knows, and then, and only then, from that foundation, begin to teach and further ‘build’ their knowledge base.

This is what most programmers who make tutorials fail to do. And it is not really their fault. With the mass proliferation of tutorials that we currently have, it is easy to forget that teaching is itself a skill. One that needs to be trained.

Without the fundamental empathy needed to meet the learner at his or her level, the teacher, in this case, the tutorial maker, will simply be making too many assumptions, based on his own level of knowledge and therefore be building a structure on a foundation that may not even be there.

This is very often the case with programming documentation in particular.

Ever had to Google most of the missing pieces in an installation process, simply because the author had assumed that you already knew certain parts of it? I know I have, on numerous occasions.

So how does one solve this? How do you go about 1. Gaining the empathy with the learner necessary to create a great tutorial. And then 2. Effectively teach and ‘build’ on the learners existing knowledge structure?

Let’s start with 1.

How To Gain Empathy With Your Learner As A Tutorial Maker

The sheer amount of ‘foundation’ or level of knowledge that is needed nowadays, means that the depth of the research process that you undertake as a teacher must strive to match it.

Fortunately, we live in an era where the level of depth in one’s research that can be achieved is relatively high.

By depth, I am referring to the amount you can know about your learner’s current level of knowledge.

The way in which you will do this will be two-fold.

  1. Target a specific type of learner. Know who exactly it is that you are trying to teach.
  2. Gain empathy for the learner’s level of Knowledge. By building a mental model of the current foundation that the learner has.

To achieve one, you must simply try to visualize in your mind’s eye, a specific person that you would like to share knowledge with. In this, you must be very specific.

The best person to target in most cases is yourself, as you have an infinite amount of knowledge about this demographic.

Doing this well will reveal many of the traits as well as the likely habits of the target learner. This arms you appropriately to be able to do the next step.

Once you have gotten yourself a clear enough picture of who you would like to teach, the next step is to gain empathy with the target learner and then gradually build a mental model of their current level of knowledge. This is done by seeking out the places where your target learner hangs out. This can be on sites such as Reddit, but even YouTube videos and comments, as well as things like Amazon reviews, can serve as good sources. Anywhere your target learner is likely to be and has an impetus to be active in some way (such as by making a comment) can work well.

Once you’ve done this, simply observing them and over time, gradually building up your mental model, you will begin to slowly develop a clearer picture of your learner’s current knowledge structure. This can take as little as a day to a week, depending on your level of skill in this, as well as how much your mental model already matches that of the target learners.

Once you have gotten yourself this synchronicity with your learner. You are now able to move on to the next step.

You are now ready to teach.

How To Teach Effectively, The Constructivist Way

We learn best when our neurons get ‘switched on’, or activated.

This activation of neurons then helps to facilitate the ‘linking’ or ‘absorption’ of new information that occurs when we learn. 

Neurons are best activated by novelty. Learning or experiencing something new. Like a new language or framework, for example. 

What this activation does is simply prime the brain for information storage. 

It gets it ready to build on the knowledge structure.

Once this happens, the brain then begins to store the new information by following a process of searching for pre-existing information within the brain and then linking or ‘associating/absorbing’ the new information with the MOST similar information to it it can find. Ultimately building a new knowledge structure or concept. 

The key words in the last paragraph are ‘searching’ and ‘most’

You see, the more similar the associative link is that the brain uses, the faster, and more efficiently the brain can absorb that new information. Because the brain can now leverage the other related relationships that that link has, which are likely to be similar to the relationships inherent in the representation of the new information.

For example: Let’s say that you just saw a spoon for the first time.

Your brain wouldn’t store that new information as simply a spoon just like that. It would have no basis upon which to do so. 

It would instead first look for what it already had stored in there that was similar to a spoon, say, a fork, and would then store the spoon as a fork-like-thing, in relation to the fork. The representation of a spoon in the brain would then actually be attached to the representation of a fork. They would be linked – neuron to neuron. And in that process, the learning of a spoon as a concept represented in the mind would occur.

The brain then, would interpret a spoon to be something like a fork but with a rounded top and no gaps. The concept of a spoon could only be ‘learned’ or said another way, ‘absorbed’, and then subsequently exist in the brain, as an extension of the concept of a fork.

So using this example of the fork and the spoon. The only truly new information that needs to be stored is that of the top side of the spoon and its difference with the fork. The brain leverages the knowledge of the bottom side (the side you hold with your hand), and saves the energy of having to store that again. If you now, on top of priming the brain with novel information, like a new programming language or framework, present that new information with the best associations that the brain can leverage, such as the most similar languages and frameworks to the novel one, you effectively eliminate the searching process that the brain has to typically go through on its own. With the end result that you massively increase the speed of absorption and learning.

This is what we mean in practice when we talk about teaching with a constructivist approach.

The emphasis is on first, gaining empathy enough that you can see the pre-existing knowledge structure in your learner that can be leveraged. And then once you’ve grasped that, pulling on that structure in order to efficiently store new information into it.

This approach, if applied well, can make your programming tutorials and documentation easier to understand for your learners, and simply that much better overall.

—-

This is the style of teaching that we use within our books and courses at FromToSchool.

We are creating the first programming books that aim to focus strictly on teaching new technologies to experienced developers, using the languages and the frameworks that they already know. No brain searching needed. 

Our goal is to not only allow developers to increase their learning speed in order to keep up with and match the speed at which technological change is taking place, but to surpass it. Be sure to check out our books and courses if this approach and article interested you and you’d like to learn more.

You may also subscribe to our email list below to be the first to know when we publish a new post or book.


What Is WebPack In VueJS & What Is It Used For? A Simple, Jargon-Free Guide

Do you remember in jQuery how when you wanted to add additional functionality than was provided, you would have to load in library after library in order to get what you wanted?

After a while, it probably became very cumbersome to manage didn’t it?

It probably ended up looking something like this: 

[image of too many script source tags loaded in]

You would have to add in a bunch of different script tags, load them into the relevant documents, and then on top of that, make sure that they weren’t conflicting with each other. Which they unfortunately, usually were. And then when they were, you were given highly obscure error messages at best in order to deal with them.

In VueJS, while you are able to do things in the jQuery multiple script src tag way, there is an alternative that is also available.

That alternative works from the command line.

That alternative is Webpack.

What Is Webpack In VueJS?

While Webpack is infact available to any JavaScript based project, we are only, for the purposes of this tutorial, going to focus on it as it pertains to VueJS.

Before we get into what Webpack is, we first must understand why it exists in the first place. We will know that by understanding the problem that Webpack solves.

The Multiple Scripts Problem & How Webpack solves this

What Webpack fundamentallly does is make your VueJS (along with a variety of other frameworks) development process easier. 

Before we get into how it does this. Let’s first take a step back and understand why Webpack exists in the first place. 

As the web evolved, two fundamental problems began to emerge for developers. 

  1. Too many libraries. To meet the UI demands of the modern web (link to post that explains why here), more and more external libraries and plugins were needed within projects. This got to a point where you could be needing more than 100 external libraries for your project at any given time. Sometimes many more. Imagine 100+ script src additions within your html file. This would be unmanageable.
  2. Speed increasingly becoming important. To respond to the increasing demand for performant, responsive, desktop-app like UI’s that was now necessary for the modern web, many developers DID opt to go for simply adding in a bunch of libraries directly. This, as you can imagine, lead to increasingly slower and slower UI’s and load times. This also lead to a dramatic decrease in the user experience. I think you can probably remember this time period. It was around 2011/2012 when jQuery was just reaching its peak. In response, many services such as Google, responded by imposing penalties for sites that were deemed to be too slow for the user, so that the fastest sites ultimately rose to the top. The consensus gradually became that the web and its websites just had to get faster, no matter how many libraries needed to be loaded. The web needed to become more efficient. Knowing how the economics of the web work, especially when Google institutes a penalty, the result of this became that web developers now made speed a priority. 

To respond to all of these increasing concerns a solution, ideally, a simple one, was needed.

In came Webpack.

How Webpack solves the multiple scripts problem

Instead of having to load in multiple libraries and manage them in an obscure way, with Webpack, you could now simply load in and manage your libraries within your command line. Using what is known as a ‘build’ script. These libraries would be loaded and stored within discreet folders in your project library and then made easy for use and loading when necessary.

Webpack would also make it easy for you to compile your newly loaded web libraries, so as to make the speed at which these libraries load much better. As well as this, Webpack would allow you to use new JavaScript functionality (such as ‘require() for modules’) within your code that was not readily available in modern browsers.

It could do this because you could write the code you wanted in your pre-compiled, or ‘built’ scripts, and then once you were ready, you could ‘build’ and compile them down into a format that the modern browsers could read and understand. Thereby unlocking a massive amount of new functionality.

While Webpack fundamentally is a JavaScript library bundler, it also allows for more useful functionality to occur during that bundling process.

Functionality such as:

  • Linting. Which is the analysis of your code for any potential errors.
  • Custom Loaders. Because Webpack by itself only understands and compiles JavaScript, custom loaders can be introduced to it in order to allow for the understanding and compilation of more types of resources such as CSS and images.
  • Plugins. Which allow for custom tasks to be run on your scripts at compilation time, such as the injection of custom data (ie. environment variables) and/or the custom optimization of your compiling bundle.

All of the above can be summarized as part of the hook functionality that Webpack provides. This basically creates a way to ‘hook’ into the bundling/build process as it is going on and manipulate your scripts in various different ways, with various processes, such as the ones listed above.

How To Use Webpack (Within A VueJS Project)

How Webpack works within a VueJS project

Just like the starting point of any Vue app is in the initial Vue instance. Likewise, the starting point of any Webpack build is in what is known as the ‘entry file’. This is simply the file that is specified within the webpack.js.config file as the place that Webpack should read to find and then bundle our imported modules.

In the case of a Vue project, this entry file is usually the ‘{}.js’ file. We will jump into this in the demo project in a minute, but before we do that, let’s get a reminder of what loading in libraries (modules) is like without Webpack.

Vue without Webpack

Vue without Webpack or any other bundler, looks a lot like jQuery in terms of folder and file organization.

You simply have a lot of libraries being loaded into the pages that need them, one by one. Usually within your header section in your HTML page. Like this:

<!DOCTYPE html>
<html>
    <body>
        <h1>Your Non-Webpack VueJS Project</h1>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js">
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">
        </script>
    </body>
</html>

Here you can see that we are directly loading in our standard VueJS script and then below that we are loading in our Axios library. Which is a popular library that simply allows us to run HTTP requests.

Note: In Vue as well as in other well known JS frameworks, what we normally used to call libraries are now commonly referred to as ‘modules’. This is largely due to the influence of Node.JS and the way in which these libraries are presented within the code.

They are typically loaded in, as we will see below, in the way that ‘modules’ in other languages and frameworks, such as Python do.

We may use our loaded in Axios library above, like this:

<div id="app">
  {{ info }}
</div>

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})

You will note here that the above seems pretty straightforward. But remember that we are only loading in one library. In most projects that are required to meet today’s modern level of complexity, as much as 20-100 different libraries could be needed. Sometimes much more.

Since we need them all. The best thing to do to make them manageable is to simply bundle them up and automate this process so that we are not having to deal with each one, one by one. This is what we do with Webpack.

Vue with Webpack

Using Webpack changes the way that you both write your code, as well as the way in which you organize your folder structure.

While in our previous ‘without Webpack’ example, we could get away with putting everything in one page, and simply loading in our libraries from a CDN. Doing this massively limits the potential of our application and what we can ultimately do as developers.

This style of organization, both in terms of code and overall project structure is simply too primitive to deal with the demands that modern website building entails.

The Modern web project code and folder structure, and how it all works (In Vuejs)

The folder structure

The easiest way to get started with Webpack within your Vue project is by using the ‘Vue CLI’. Check out the link to learn more about that if you don’t know already. We will skip the installation and jump right in.

This is the typical folder structure that we get from a full Vue project, installed using the Vue CLI.

[image here]

Within this structure, our Webpack basically coordinates everything that we’ve described above from within our webpack.config.js file. This is our command center. It is here that we set our ‘hooks’ such as our loaders (in this case we have our Vue loader set within it), as well as all of the other necessary plugins we need.

Loading in and managing libraries (modules) with Webpack within this structure is as easy as running ‘npm install {package you want}’ while within our newly installed Vue folder directory, in the command line.

In this case, we will load in Axios.

Navigate to your VueJS folder directory and type in ‘npm install vue-axios’.

This loads in and places our Axios library within the ‘node_modules’ folder within our directory.

The File Structure

Once we have done that, we will simply add in our imports of Axios in our Vue ‘entry file‘ {name of the file}, like this:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)

What this basically does is place a reference for Webpack to know (as it has already been specified within our webpack.js.config) that we will be reading this file for modules that need to be loading in and bundled at compile time.

All of our loaded modules in the future will be referenced within this entry file.

There is no need to load in anything else after that. When we have written the code we need. We will simply compile with our Webpack enabled command, in this case, ‘npm run dev’ and it will handle everything else that is necessary to get it to work with our code.

Let’s now use our newly loaded library in an example to demonstrate what we mean here.

Let’s open up our App.vue file. We will be making a call to an API and then displaying our data to our root <div>.

[example code of the App.vue file]

Notice that the only things we have in this page is the code we need. All of the other parts of the code, such as the header, footer and other libraries are going to be bundled in once we run our Webpack script.

When we’re ready to view this code, we will simply run this script. Like so, within our command line, inside of the project folder: ‘npm run dev’.

This will bundle up our code, from its present and then push it to the dist folder as browser recognizable JS, CSS and images.

As you can see here. Webpack is not only allowing us to load in our libraries in a very easy way but it also, with the additional functionality it adds via its ‘hooks’, the loaders and plugins, allows us to unlock amazing functionality at a higher level in our projects, such as the ability to use custom ‘App.vue’ files and structure our projects in the way that this makes possible. Via the Webpack ‘Vue Loader’ in this case.

Webpack ultimately is a key component of the modern web. With the ever-increasing complexity that most developers have to now deal with and the endless array of tools that need to be managed, making the process of bringing them together and working seamlessly, as well as adding more useful, efficiency generating functionality on top of that, only make it greater.

With Webpack, your workflow, especially in VueJS, which is already making things easy, makes it just that little bit easier.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below


What The Vue Instance Is, And How It Unlocks The Magic Of VueJS

What Is The Vue Instance?

Before we can start to do anything with VueJS on our webpage, we first need to create a way for Vue to initialize and then ‘bind’ itself onto that page.

Just as in jQuery, nothing happens until we initialize our document ready function, like this:

$( document ).ready(function() { console.log( "ready!" );});

In Vue, nothing happens until we create our Vue Instance, like this:

<script>
new Vue({
    el: '#app'
    data: {
        
    }
})
</script>

Within the bounds of this Vue Instance, which is just a simple JavaScript object, we can write the code that Vue will recognize and then execute onto the page.

Let’s first take a deeper look into what is actually going on with this Vue instance object, and then we will talk more about what it can allow us to do on our HTML page specifically, and how it unlocks the magic of Vue.

Inside The Vue Instance Object

On the first line, we begin with the instantiation of our class object, which bears the title of Vue, like this:

new Vue({ }}

This creates and initializes the Vue instance within our browser.

Next, within our created Vue instance, on the first line of our object, we add in our ‘el’ option, which looks like this:

new Vue({
    el: '#app'
})

What this ‘el’ option does is simply ‘bind’ our Vue Instance to an element within our HTML (in this case, one with an ID of ‘#app’), allowing us to apply our Vue functionality to everything that is within that element.

Putting it all together, it would look like this:

<div id='app' </div>

new Vue({
    el: '#app'
})

As you can see, our <div> element, with an ID of ‘#app’ has been bound to our newly created Vue Instance. Another way that we can refer to this ‘binding’ of an element by Vue within the Vue instance is as a ‘mounting’ of, or to ‘mount’, an element. It means the same thing. Simply that we have attached our Vue instance to that element, in order to activate Vue’s functionality within that element.

A key difference to note here, coming from jQuery, is that rather than applying functionality to the entire webpage, as is done with jQuery, in Vue, functionality is only applied to a specific section of the page – one that is bound to a Vue instance (of which there can be many). In this case, our <div> element, with an ID of ‘#app’.

Lastly, we have our ‘data’ option. Which as you’ll see soon, is one of the most important parts of our Vue instance in terms of functionality. It looks like this:

new Vue({
    el: '#app'
    data: {
        someText: 'helloThereText'
    }
})

As you can see here, after creating our Vue instance and then mounting it onto our ‘#app’ element, we then set some data within our instance. This gives our mounted <div#app> element access to the data that is within our Vue instance object.

That data can now be used directly within our mounted HTML element, like this:

<div id='app'>{{ someText }}</div>

By placing the data variable from our instance within double curly braces, we allow Vue to recognize and then ‘interpolate’ the data as being from our Vue instance, in the example above. This data is then transformed into the text that it contains within the mounted HTML element.

On page load, the data held within our ‘someText’ variable above will be displayed out onto the loaded page as the text, ‘helloThereText’.

How The Vue Instance Unlocks The Magic Of VueJS

So from the example above, we can see that a Vue Instance is basically an object that is created in order to allow us to attach Vue functionality to our HTML.

Let’s now take a slightly closer look at what the Vue instance is and what it can do. The explanations below will aid you greatly in getting a deeper understanding of what Vue can do for you, and in general, what Vue is all about.

A Data-Driven Approach To UI Manipulation

Because Vue is primarily ‘data-driven’, which means that what happens on the page is simply a reflection of what happens in the data held by Vue, along with the changes to that data, the Vue instance can be thought of as a syncing agent that simply translates changes in the data held by Vue, to changes in our UI. And by doing so, keeps our data -> view connection ‘in sync’.

An example of this can be seen with the way that view allows us to handle conditional logic on our HTML page.

Below we are displaying or hiding an element within our Vue instance, depending on whether or not data (as a variable within our data object) is set to either true or false.

<div id='app'>
    <h1 v-if="is_it_true">{{ someText }}</h1>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            someText: 'helloThereText',
            is_it_true: true
        },
    });
</script>

In the current way that it is set up (with Vue’s v-if attribute, Vue attributes allow us to add Vue functionality directly to our HTML elements), our h1 shown above will show on page load. With the text ‘helloThereText’.

If we were to change the value held by our is_it_true variable within our data option to false, the h1 will disappear.

This is what we mean when we say that Vue is data-driven. It is driven, and changes on the webpage are made, by what happens in the data that is held by its instances.

The Vue instance, by giving us a simple ‘command center’ where we may set, and when necessary change our data, helps us to unlock the magic that is data-driven Vue.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below


What Is The DOM – (Book Excerpt – From jQuery To VueJS)

Imagine that you just hand-wrote a thousand-word Essay on the oh so glorious language of JavaScript. 

After you had finished that Essay, you decided that you wanted to change the first paragraph’s font color to red. To make it stand out more. 

Now, imagine that you had magical powers. And that you could simply do this by taking your hand, plucking the paragraph with your fingers, rubbing the paragraph in your palm to change the color, and then setting it back down onto the page. Wouldn’t that be awesome (and also a pretty cool party trick)?

This is essentially what the DOM allows you to do with web pages. In the case of the example above, the DOM would be the hand that allows you to pick up, manipulate and drop the elements and/or contents of those elements. 

The DOM is essentially an interactive layer that sits on top of a web page and makes it easier to interact with that page.

Within the DOM the elements and contents that we are referring to are called ‘nodes’. These nodes exist on a tree-like structure, that is best visualized as a flowchart. 

You can see an example of this here: [highlight what the different numbers mean – 9 signals document type, 1 signals an element, 3 signals content, and so on and so forth.]

What we have above is the general flow of a HTML document that is created and represented within the DOM. This is essentially how the DOM ‘sees’ a web page.

It is, essentially, an API for the Web Document, whether that document is in HTML, XML or another compatible format.

The DOM is like the fingers that allow you to pluck, structure and then interact with the elements from a page of an essay you just hand-wrote on a piece of paper, and manipulate them how you want, and then put them back onto the paper. Except in this case, that paper is the web.

To be the first to know when we publish a new post or book, you may also subscribe to our email list below