Vue.js Intro – The Progressive JavaScript Framework

1

Another JavaScript framework? Yes? Do not worry, Vue.js is different. The lean library serves all niches that were previously ignored by framework developers, and thanks to the incrementally usable additional libraries from the environment also all other common cases with the same.

Even the genesis of Vue.js is different. Behind the new star on the JavaScript sky this time is not a large corporation or social media house, but an individual. Evan You has worked as a Creative Coder for Google Creative Labs, but his JavaScript framework was created in his own interest. After the release in 2014, the popularity of the library increased. The release of version 2 in September 2016 has then established Vue.js among large companies. Meanwhile, through sponsors, OpenCollective and Patreon donations, Evan You has been able to work full-time on Vue.js for over two years, as evidenced by progress and stability.

But what can Vue.js do that others can not? For the remainder of the article, let’s stick to two concepts: progressiveness and incremental usability. Vue.js can be used for parts of an existing application or website, but also as a complete replacement for jQuery-based JavaScript enrichment in interactive widgets. Gradually you can now switch reusable components, modern JavaScript syntax and preprocessors. From a few widgets to a complete application, the library’s extensive ecosystem can boast authentication, routing, and state management. Just like the big ones!

Hello, Vue!

In addition, you do not need a subject diploma to start with Vue.js. All you need is a 20 KB JavaScript file (minified and delivered with GZIP) and a little JavaScript. No lengthy build processes, no command line tools, no syntax extensions like TypeScript or JSX. That does not mean that these things are not all possible and available. There are also cases where it makes sense to use a more complex set-up. But for the beginning a little markup, a bit of CSS and surprisingly little JavaScript is enough. The following listings show you everything you need for a simple “Hello World” with Vue.js. We enrich our HTML file with a little markup.

...
    <div id="app">
      <h1> {{ msg }} </h1>
    </div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
    ...

Important is the unique ID app of our parent element. This element is the entry point for our application. From then on, everything is taken over by Vue.js, and we recognize the well-known template syntax with the curly brackets again. Here we expect Vue.js data named msg . Well, if you already expect that, let’s flaunt that for a moment:

new Vue({
  data: {
    msg: 'Hello World! '
  },
  el: '#app'
})

This is all the JavaScript we need. We create a new Vue.js instance and attach it to the #app element. Elements are selected using CSS selectors, as we know from jQuery. The data object is also self-explanatory. The property msg here is analogous to what we have in our template. Easy? Yes! Boring? That too. So on to something more attractive: A Counter Widget.

Interaction and reactivity

At the present time, it seems that counter widgets of the once popular to-do list in matters of demo applications have run out of rank. The reason is obvious: You can explain incredibly beautiful reactive data streams with it. Let’s take a look at Vue.js. Our goal: A small counter, which increases the current number by clicking on the PLUS button, and causes the opposite with the MINUS button.

The data object at Vue.js has a very special property. Properties in this object are not only accessible in templates, they also become reactive when creating the Vue.js instance. When a property changes, an event is triggered and all processes that should know about this event are notified of the new value. For example, expenses in the template. You already notice a bit of Vue.js magic when you want to manipulate the property. Similar to the data object, the Vue.js instance also has a methods object, as we see in Listing 1. This object stores methods that will be called later on click or other invocation options. But if you want to access the data object, a simple access through this , just like this.count. Well, this is already notoriously ambiguous in the JavaScript world anyway. Vue.js goes one better: whether it’s inline functions in templates (which are also there), ordinary JavaScript functions in the methods object or via Arrow Functions in the Methods object, this is the Vue.js every time instance. And in this instance, properties are now available that we have defined elsewhere. These properties have been created and have the property descriptors get and set . When accessing this property, Vue.js takes control of the rest of the process. So you can easily change data and output the result in the template again.

However, to call functions from the methods object, we need user input. With a little extra markup in our template, we can bind methods to events. For example, an @click = “up” on a button element corresponds to an addEventListener for a click event. Only that Vue.js here takes the work from us and also immediately recognizes which method we mean in our methods object. The final code is in Listing 1 and is accordingly manageable.

Listing 1: JavaScript and HTML

      <div id="app">
      <h1> {{ count }} </h1>
      <button @click="up">+</button>
      <button @click="down">-</button>
    </div>
....<script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
    new Vue({
  data: {
    count: 0
  },
  methods: {
    up() {
      this.count = this.count + 1;
    },
    down() {
      this.count = this.count – 1;
    }
  },
  el: '#app'
})
</script>

By attaching methods to events, we are already on the next Vue.js concept: directives.

directives

If we use @click to bind a method to an event, we’ll use the shorthand notation for something called Vue.js directives. @click in the longer version is v-on: click and is very familiar to experienced Angular.js 1.x veterans. Compared to Angular.js however, directives are only available in attributes. Like any other modern JavaScript framework, Vue.js calls components in tag-form directives. These directives now allow us to put JavaScript expressions directly into our templates and thus influence the generation of further DOM elements. The best known and most widespread are the following:

  • v-if the generation of the DOM elements depends on the positive evaluation of a condition
  • v-for repeats creating the DOM elements for multiple entries in an array
  • v-on binds methods to events, such as For example, click, keydown, submit, and the like
  • v-bind binds the contents of various attributes to a field of the Vue.js instance; we know this as 2-way data binding from other frameworks

There are many more, and you can add more if you need them. For the standard case, one is well served with the directives mentioned here. Let’s take a look at some of them in action. We want to turn our Counter Widget into something more meaningful just now: a stock management whose products have a name and a quantity . These are stored in an array in the data object. We want to show a disordered list for each element in this array. To iterate over this array, we use the v-for directive, which allows a style in the style of v-for = “product in products “. Products is the actual name of the array in the data object, Product is an alias for the currently selected element. With this alias, the element is now available in our templates.

We use the same to increase the amount of the entry with the known v-on: click or @click . A simple @ click = “product.quantity + = 1” increases the entry. Vue.js takes care of updating the data in the instance and triggering the reactive data stream.

Last but not least, we give a warning. If there are fewer than five pieces available for items in my product list, we encourage the user to increase inventory. A message in a span, which is displayed in the case of v-if = “product.quantity <5” , helps us with this. Listing 2 shows the final code.

Listing 2: JavaScript + HTML

&lt;div id="app">
  &lt;ul>
    &lt;li v-for="product in products">
      {{product.name}}: {{product.quantity}}
       &lt;button @click="product.quantity += 1">+&lt;/button>
       &lt;button @click="product.quantity -= 1">-&lt;/button>
       &lt;span v-if=”product.quantity &lt; 5”>{{ product.name }} werden knapp!&lt;/span>
    &lt;/li>
  &lt;/ul>
&lt;/div>
    &lt;script src="https://cdn.jsdelivr.net/npm/vue">&lt;/script>
    &lt;script>  
    new Vue({
  data: {
    products: [{
      name: 'Schuhe',
      quantity: 1
    }, {
      name: 'Socken',
      quantity: 10
    }, {
      name: 'Shirts',
      quantity: 12
    }],  
  },
  el: ‘#app’
})
&lt;/script>

As we can see, the JavaScript code did not get much bigger than in the previous example. The templates are very powerful, and the evaluation of JavaScript expressions in the template code itself saves a lot of function boilerplate.

Admittedly, we are still a bit far from a full-fledged single-page application, but these brief examples allow us to look at a few important core concepts of Vue.js:

  • Templates are incredibly powerful. Through directives and the evaluation of JavaScript expressions directly, whole widgets can be generated in the template code. All you have to do is define the data structure in the Vue.js instance.
  • The reactive data stream is omnipresent. Changing a value anywhere in the application directly affects the display of the value in the DOM.

However, at the last bullet point, the reactive data stream, we first scratched the surface. With watched and computed properties we see how effective this stream can be.

“Watched” and “computed properties”

The display of data has so far been relatively simple: we change an entry in our data object. This update will be displayed in the templates. So far so good. But in most cases, we also need ads that do not quite fit our data model. Take Inventory Management again as an example. It would be nice if we not only see the number of products for each entry, but also the sum of all our products in stock. For such things Vue.js has so-called Computed Properties, thus calculated characteristics. Anyone who has previously worked with Ember.js knows the basic approach.

As with methods and data, Vue.js needs another field in the instance: computed . This field now takes a number of functions and each of these functions needs a return value. If it is present, there is now a separate property in the Vue.js instance (and therefore also in the templates) that we can output – just as if this field were in our data object. The special feature is that in this function we can access values ​​of our data object and the computed property updates with changes to the original.

So if we want to have a total ad for our inventory management, we need a function called total in the computed field, which adds all existing product inventories. A change in a product inventory is also totally updated. totally , actually a function, is now also a field that we can use in our templates. Listing 3 shows the example.

But that’s not all. With Vue.js we can go one step further. Suppose we want to show totally red as soon as it falls below a defined threshold. For this we have to watch totally and depending on the value change put a class in a DOM element. With Watched Properties, Vue.js provides us with exactly this functionality.

Analogous to the remaining properties, we get a field watc h in the Vue.js instance. This field now also assumes functions. However, in the name these must correspond to a field in the data object or a computed property. The reason: As soon as a field with this name changes, it triggers our Watched Property and performs a function. In turn, we can change values ​​from the data object.

For our example, we create a property in the data object named totalClass . This field is a class name that is either normal or red . At red we should urgently increase our stock. With v-bind: class or the shorthand : class, we make sure that the class attribute on the DOM node changes when something changes in the totalClass field.

Now we create a watcher for our Total Computed Property. This method passes a parameter, the current value. If this value is less than ten, we color the totalClass red. Listing 3 shows how it works.

Listing 3: JavaScript and HTML

&lt;div id="app">
  &lt;ul>
    &lt;li v-for="product in products">
      {{product.name}}: {{product.quantity}}
        &lt;button @click="product.quantity += 1">+&lt;/button>
        &lt;button @click="product.quantity -= 1">-&lt;/button>
        &lt;span v-if="product.quantity &lt; 5">{{ product.name }} werden knapp!&lt;/span>
    &lt;/li>
  &lt;/ul>
  &lt;p>
    &lt;strong>Total quantity:&lt;/strong> &lt;span :class="totalClass">{{ total }}&lt;/span>
  &lt;/p>
&lt;/div>
&lt;style>
red {
  color: red;
}
&lt;/style>
    &lt;script src="https://cdn.jsdelivr.net/npm/vue">&lt;/script>
    &lt;script>  
    new Vue({
  data: {
    products: [{
      name: 'Schuhe',  quantity: 1
    }, {
      name: 'Socken', quantity: 10
    }, {
      name: 'Shirts', quantity: 12
    }],
    totalClass: 'normal'
  },
  computed: {
    total() {
      return this.products.reduce((acc, el) => {
      return acc + el.quantity
      }, 0)
    }
  },
  watch: {
    total(val) {
      if(val &lt; 10) {
        this.totalClass = 'red';
      } else {
        this.totalClass = 'normal';
      }
    }
  },
  el: ‘#app’
})
&lt;/script>

We see that the data stream can be quite complex. A change in our predefined data changes a calculated property. This in turn triggers an observer, who in turn changes a value in the predefined data. If you think that you can run into a cyclical dependency very quickly and even fall into an endless loop, that’s right. However, Vue.js is smart enough to notice that and just stops execution. You can tell by a comment in the developer tools.

Since Vue.js is pretty good at evaluating JavaScript expressions, you can work very comfortably as a developer and leave a lot of manual work to the framework. Updating properties is almost like voodoo, but it makes sense to look a little under the hood.

So far, Vue.js has given us everything we need for a small application. But if we want something bigger, we have to work a little more filigree.

components

Components are the big thing in SPA frameworks. React prides itself on having ushered in the age of components. Well, experienced software developers know that the modularization of various software components to reusable components has not necessarily been in vogue for a few years. But you have to admit, never before has it been easier to knit reusable UI building blocks for web applications. Vue.js is no exception.

Especially if we want an application that does not just consist of a widget and a very simple data stream, we need a lot of widgets that we can fill in different contexts with different data. Vue.js gives us the possibility to extend the existing instance with our own components. With Vue.extend ({}) we can simply copy the existing code into another object and make it accessible via a variable. We can register this variable globally with Vue.component or extra per Vue.js instance. Thereafter, the component is available as an HTML element in the application. In terms of components, there are only a few things to keep in mind:

  • Templates are no longer simply defined in HTML. Although you can use a template element and load it in the component, it is much more comfortable if you directly fill the template field in the component. Incidentally, this field is also available for a Vue.js instance if you want to save your way via the HTML.
  • There is no data object anymore. This is because output data is only defined by instance. The individual components have a data function and in turn return an object. One notices that components must now be instantiated extra.
  • Another property occurs: you can define your own attributes. The field props defines an array of strings that are just waiting to be filled with data from outside. So we can keep the products field, but fill it with different products.

In Listing 4, we see how we’ve made our inventory management a multi-category manager, thanks to the my-counter component.

Listing 4: JavaScript and HTML

&lt;div id="app">
   &lt;my-counter :products="clothes">&lt;/my-counter>
   &lt;hr>
   &lt;my-counter :products="sweets">&lt;/my-counter>
&lt;/div>
&lt;style>
.red {
  color: red;
}
&lt;/style>
    &lt;script src="https://cdn.jsdelivr.net/npm/vue">&lt;/script>
    &lt;script>  
const Comp = Vue.extend({
  template: `&lt;div>&lt;ul>
    &lt;li v-for="product in products">
      {{product.name}}: {{product.quantity}}
       &lt;button @click="product.quantity += 1">+&lt;/button>
       &lt;button @click="product.quantity -= 1">-&lt;/button>
       &lt;span v-if="product.quantity &lt; 5">Buy more {{product.name}}&lt;/span>
    &lt;/li>
  &lt;/ul>
  &lt;p>  
    &lt;strong>Total quantity:&lt;/strong> &lt;span :class="styleClass">{{ total }}&lt;/span>
  &lt;/p>&lt;/div>`,
  props: ['products'],
  data() {
   return {
     styleClass: 'normal'
   }
  },
  computed: {
    total() {
      return this.products.reduce((acc, el) => {
        return acc + el.quantity
      }, 0)
    }
  },
  watch: {
    total(val) {
      if(val &lt; 10) {
        this.styleClass = 'red';
      } else {
        this.styleClass = 'normal';
      }
    }
  }
});
new Vue({
  el: "#app",
  data: {
    clothes: [
      { name: 'Shoes', quantity: 1 },
      { name: 'Socks', quantity: 10 },
      { name: 'Shirts', quantity: 12 }
    ],
    sweets: [
      { name: 'Chocolates', quantity: 10 },
      { name: 'Candy', quantity: 5 }
    ],
  },
  components: {
    'my-counter': Comp
  }
    })
    &lt;/script>

In this way, we are approaching a single-page application in large steps. However, these steps are what make Vue.js special. We can go on step by step in our application. From the simple widget, through a widget with dependency on the output to the reusable component. Everything in one framework, and everything gradually unlockable. For a full-fledged application, we need even more. And this is where the Vue.js ecosystem comes in.

The Vue.js ecosystem

The extensive ecosystem of Vue.js is one of the reasons why the framework is so popular with developers. Unlike Angular, the base framework is very lean and manageable, and has few basic building blocks that you would expect in full-featured single-page applications. These can be used as required by additional modules. Vue.js is not that dissimilar to React, but it has one major difference: Vue.js comes from a single source, from Evan You and its core team. The most important building blocks are listed here:

vue-router solves the omnipresent problem of single-page applications: if you deliver only one HTML file, you only have one URL. A clean router, however, assigns URLs to various views and status in the application. In the application the router of Vue.js is correspondingly simple. Routes are defined by components. This will become a component to the view. Attaching the router to Vue.js, we get components like route r-link and router -view. A click on a router -link thus changes a router -view and matching the URL in the address bar. Conversely, the Vue.js router also listens for changes in the address bar and updates the view according to its scheme.

Of course, features like dynamic matching or nested routes are all included. In fact, the router has its own documentation, which is available on the homepage of Vue.js. From simple demos to complex animations everything is included here.

If you know React, you love things like Redux. State management, which assumes a global state for the entire application, is one of the things that has made SPA development so easy and accessible in recent years. With Vuex Vue.js offers its own state handling. The data object becomes almost obsolete, everything is controlled by a global store, which can be changed via unique events such as actions and mutations. The output in templates is then solved via computed properties . This is a bit more complex than Redux in the application for simple examples, but very powerful and, above all, very well tailored to Vue.js when it gets more complex overall. As with the router we get on the homepage of Vue.js a very good documentation .

When it comes to performance, it is above all the time that elapses from the start of the request to the presentation of data on the monitor. The shorter, the more likely the user feels that something is happening. In order to be able to shorten this time particularly well, it is worthwhile not to render everything in the browser, but perhaps actually to display data with the first transfer of the document. Under the term “Server Side Rendering” this behavior has become popular again. Vue.js offers a Node.js module called vue-server-renderer. This makes it possible to create Vue.js instances without browser context and send results as HTML via the Node.js server.

These outputs can transition into an interactive context by sending the same application to the browser. Also for this there is a separate documentation of Vue.js , and you will also find, if you want to use his favorite Node.js server framework with Vue.js.

With that, we are already approaching a full-fledged single-page application in terms of features. We can quickly render views and change them depending on the URL (and vice versa). A global data store ensures that we always know in which state our app is currently located. But if you want to scale as a developer with your application, you need a little more than a few JavaScript files and laborious handwritten code. Vue.js also has something in store for it: With the vue -loader plug-in for webpack it is possible to create your own .vue files, in which one manages templates, JavaScript code and styles in single file components. quite similar to the web components of polymer. So you can structure your application as you like and even write CSS only on a component basis. Listing 5 gives an example.

Listing 5: “Hello.vue”

&lt;template>
  &lt;div id="hello">
    &lt;img src="http://vuejs.org/images/logo.png">
    &lt;h1>{{ msg }}&lt;/h1>
  &lt;/div>
&lt;/template>
 
&lt;script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
&lt;/script>
 
&lt;style scoped>
#hello {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
   
text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
a {
  color: #42b983;
}
&lt;/style>

The great thing is that the vue-loader can be combined with other webpack loaders. So with a few keystrokes you can easily add things like Sass, LESS, TypeScript or something similar. That leaves you with your favorite languages, but has all the power of Vue.js underneath. So nothing stands in the way of an extensive SPA.

Conclusion

Vue.js may not be the most innovative framework, but it does two things right. For one, it does not get in the way of oneself. You can write really nice widgets and applications very quickly and without great effort. The learning curve is low, the reward feeling enormously high. Beginners will enjoy Vue.js, especially because you can do without a build step.

On the other hand it is difficult in Vue.js to find something that does not work. If you want templates and directives like in Angular, you’re right with Vue.js. If you want to write Vue’s reactive data stream but still in the React environment common JSX, it costs only a few lines of configuration code in the build process. Each preprocessor is supported, and it’s easy to switch from any learned system to Vue.js.

Vue.js also scales with the demands of the team and the knowledge of the developer and is well received by developers or the community. At least until the next one turns the corner and makes everything better and easier.

Source: https://entwickler.de/online/javascript/vue-js-javascript-framwork-einfuehrung-579850224.html

Share This:

1 Comment

  1. Pingback: Vue.js Intro – The Progressive JavaScript Framework – FrontNet – Javascript World

Leave A Reply

Powered by FrontNet