Showing posts with label Vue.js. Show all posts
Showing posts with label Vue.js. Show all posts

Friday, 7 September 2018

"The Vue Handbook" Annotations - Part 2: Vue CLI and intro in Vue Components

This is the second article in the series of my annotations to The Vue Handbook. It covers the Vue CLI (command line interface), CLI applications and components. If you missed reading the first article (which covers the introduction in Vue.js and creating the very first application) go here.



What is Vue CLI?

  • command line utility 

What is Vue CLI used for?

  • to speed up development - it provides initial Vue.js project setup and scaffolding application skeleton with a sample app in place
  • vue-cli README on GitHub
  • makes sure all the tools you need are working along

How to install Vue CLI?


Vue CLI can be installed via:
  • npm
  • Yarn


Installing Vue CLI via npm

  • https://cli.vuejs.org/guide/installation.html
  • package name changed from vue-cli (in v1 and v2) to @vue/cli (in v3)
  • Vue CLI requires Node.js version 8.9 or above (8.11.0+ recommended).
  • https://www.npmjs.com/package/@vue/cli

    Commands and output in terminal:



    How to test that Vue is installed and check command line arguments?



    How to check Vue's version?




    How to create a Vue project with CLI?


    Vue project can be created by using:
    • only a command line (vue create)
    • browser-based UI (vue ui)
    Read: 


    How to create a Vue project from command line only?


    The Vue Handbook uses the name "example" for the new application so let's follow it:



    First select if you want only default or extended tooling to be installed

    Custom toolset selection

    You can add more plugins later by using vue add.

    Linting tools selection



    Linting features selection

    Configuration location options

    Vue app setup can be saved and reused for setting future projects
    Running the setup
    This is the entire terminal output:



    I don't have Yarn installed so I assume that is a reason this wizard didn't ask me if I want to use npm or Yarn and it automatically selected npm.

    To see which scripts can be run we can use:



    And indeed, package.json contains scripts object with CLI commands listed above:


    This is the role of each of them:
    • serve (short of service) - starts a dev server, compiles and hot-reloads for development 
    • build - performs production build  (compiles and minifies the code); prepares the project for deployment in dist/
    • lint - lints and fixes files

    What is hot reloading?

    Hot reloading only refreshes the files that were changed without losing the state of the app. For example, if you were four links deep into your navigation and saved a change to some styling, the state would not change, but the new styles would appear on the page without having to navigate back to the page you are on because you would still be on the same page.[source]

    The idea behind hot reloading is to keep the app running and to inject new versions of the files that you edited at runtime. This way, you don't lose any of your state which is especially useful if you are tweaking the UI. [source]

    How to run example app? As the last lines in the terminal output suggest, lets run serve:



    If we navigate browser to the given local URL, we can see our Vue CLI application:


    To terminate local web server, go to terminal and press CTLR-C.

    My repository for this app: https://github.com/BojanKomazec/the-vue-handbook-demo-cli-example

    So, let's explore files in the created project:



    index.html:
    • main app file (Vue CLI by default uses main.js and index.js as its entry point)
    • contains div with id="app"; we'll attach to this div a new Vue application

    Before we analyze other files, let's learn some more of the Vue stuff:

    What are Vue components?


    Components are reusable blocks of code that can have both structure and functionality. They help create a more modular and maintainable codebase. (...) In a Vue application, we don’t want all of our data, methods, computed properties, etc. living on the root instance. Over time, that would become unmanageable. Instead, we’ll want to break up our code into modular pieces so that it is easier and more flexible to work with. [source]

    Components are reusable Vue instances with a name. [from Components Basics; read here a quick intro in the logic behind how are components created and used]

    The main/root instance is the root component, it has no parent component.

    See some examples of Vue UI components.


    How to define/register Vue component?

    • programmatically (new Vue() and Vue.component())
    • via Single File Component (.vue) file


    Defining components via Vue.component()


    Programmatical definition of Vue component is done by calling a function Vue.component(component_name, properties). properties object contains:

    • HTML - as a value of template property.
    • JavaScript -  as a function which is a value of data property.

    Example:



    Defining components as Single File Components


    Files with .vue extension are Single File Components - self-contained components that have all they need in a single file. .vue file contains:
    • HTML - within <template> element.
    • JavaScript - within <script> element.
    • CSS - within <style> element. CSS can be scoped (<style scoped>) or not. 
    Example: src/components/HelloWorld.vue (analyzed later in this article)


    What is scoped CSS?


    Scoped CSS means that CSS is targeting the component uniquely, CSS won’t leak to other parts of the page, it is limited to this component only. CSS is scoped when style tag has scoped attribute.

    We can now better understand a global picture - a Vue application.

    What is Vue application?


    A Vue application consists of a root Vue instance created with new Vue, optionally organized into a tree of nested, reusable components. All Vue components are also Vue instances, and so accept the same options object (except for a few root-specific options). [Creating a Vue instance]


    HelloWorld.vue:
    • a Vue component
    • implemented as Single File Component
    • outputs a set of links, along with a message
    • has scoped CSS
    • name property has value 'HelloWorld'. This defines a custom HTML element with this name and which can be imported to another component simply by stating <HelloWorld/>
    • props (properties) object contains custom property msg. This defines msg as a (custom) property of HelloWorld (custom) element. When using this component elsewhere we'll write: <HelloWorld msg="whatever"/>
    • The message the component outputs is stored in the data property of the Vue instance, and outputted in the template as {{ msg }}
    • Anything that’s stored in data is reachable directly in the template via its own name. We didn't need to say data.msg, just msg.

    So, who is using HelloWorld component and how? Let's look into the next file.

    src/App.vue


    App.vue:
    • a Vue component
    • implemented as Single File Component
    • has global (non-scoped) CSS
    • imports another component (HelloWorld) simply by adding <HelloWorld/> element. HelloWorld is a dependency of App.

    Who is using App component and how? Let's look into the next file.




    main.js:
    • application's main script
    • creates a Vue application (creates Vue instance via new Vue(...)
    • imports App component by specifying it in the value of components property in application's options object 



    Monday, 3 September 2018

    "The Vue Handbook" Annotations - Part 1: Introduction and the first Vue.js app

    Driven by professional needs and my curiosity, I decided to start learning Vue.js. It is a very popular JavaScript framework which can be used for UI development of variety of products, from web front-end, browser extensions to native mobile and desktop applications.

    I decided to start my journey by reading The Vue Handbook: a thorough introduction to Vue.js by Flavio Copes. I will use a series of blog posts to track my learning progress and document annotations to this book I find useful to me and to other readers.

    So, let's start.



    Introduction - General info about Vue.js


    Vue.js is a progressive framework meaning that it allows initial intervention at small pieces of code with no need to change existing architecture which can gradually expand onto the entire view layer.

    It uses Virtual DOM (idea taken from React but in Vue has better performance and it's easier to use)
    Vue uses HTML template syntax. Think of it as the syntax extension of HTML which facilitates dynamic binding of values in user-facing elements and underlying components that contain data. Many similar frameworks have such concept:
    • Angular template syntax
    • Handlebars
    • The Django template language (this is Python but general explanation about templates applies to Vue as well)
      • Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.
      • A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).
      • A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.
      • Variables look like this: {{ variable }}. When the template engine encounters a variable it evaluates that variable and replaces it with the result.
      • React does NOT have templates! Here's why. It uses JSX.
        Vue's official state management library is Vuex (vuex package). It follows the Flux architecture [docs],


        What is state management in front-end?
        • What does state-management even mean and why does it matter in Front End Web Development with frameworks like React or Vue?
          • In front-end programming, one of the most essential demands is that the UI/display always reflect current application state, especially as state changes in response to user interaction. Binding JavaScript values to the display (the DOM) is the essence of React, Vue and Angular.
          • (...) create an architecture in which all the values in state are stored in a central location, with their current values funneled down to whatever components display these values. Thus modern state management of the Flux/Redux/ngrx model demands the creation of a “store” — a centralized object where all of the values in state are collected.
          • The key idea (...) is to make sure that state (meaning any one or more of the values in state) cannot be changed except by defined “actions” that are processed by a “reducer” function. The idea is to create a definite and exclusive list of ways in which state can possibly be changed, and then to process these actions in a distinct sequence.
          • Learn State Management
          • State Management

          Its routing package is: vue-router


              The very first example


              Source:


              Page with console log:


              Vue is like a glue between a UI (subset of DOM elements that are matching UI template) and underlying data. Each instance of Vue binds together UI template with data source in a fully reactive way: as soon as data is changed, matching DOM elements are re-rendered.

              new Vue() creates a (root) instance of Vue app [Creating a Vue Instance]. Its argument is an options object. In the simplest case it has to define two main things: DOM elements and data source.
              • el - provides the Vue instance an existing DOM element to mount on. It can be a CSS selector string or an actual HTMLElement. The provided element merely serves as a mounting point. The mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to <html> or <body>. [el]. In our case the Vue instance will be bound to a div element with id "example".
              • data - The data object for the Vue instance [data].
                {{hello}} is a template and hello itself is template variable which gets evaluated into value of the data member with the matching name. Personally, I would have used some different name for this variable like message for example as 'hello' is actually a kind of a message text.
                  Let's test reactiveness by modifying the source code by naming the Vue application instance. This will allow us to access and modify its properties from the code or from the browser console.

                  Source:


                  If we modify data, we can see how text in the bound DOM element changes instantly:


                  Vue.js script is downloaded from the URL https://unpkg.com/vue used in script tag. unpkg is a global CDN used for distribution of various JavaScript packages. If you type in the browser the same URL and append a slash to it, you can see the latest available version of that package and its files:

                  If we check the Sources tab of our index page, we can see that exactly this version has been downloaded. We didn't specify any particular Vue version in the URL so the latest version was fetched:




                  Read the next article in series: "Part 2: Vue CLI and intro in Vue Components"

                  Sources:

                  The Vue Handbook: a thorough introduction to Vue.js
                  A Comparative Study of Progressive JS Frameworks: Angular.js & Vue.js