Vue.js Studies Day 6 – Beyond “Getting Started”

The previous post to this one, just included some definitions to ensure I’ve covered the core topics as I’m moving along. Before that I covered getting a project app started in day 3 and day 2 posts. Before that I covered the curriculum flow I’m covering in these studies.

Now that I’ve covered a number of ways to get started with a Vue project with; JetBrains WebStorm, hand crafted artisanal, or via NPM it’s time to start covering the basics of how to build an app using Vue.js. I’ll be using the WebStorm IDE for development but will still call out where or what I’d need to do if I were working from the terminal with something else. By using the WebStorm IDE, I’ll also be starting from the generated app that the IDE created for me.

main.js

Starting in the src directory of the project, let’s cover a few of the key parts of this project of the application as created. First, we have a main.js file. In that file is the following code. This little bit of code is what is responsible for working with the Virtual DOM to mount the application to it for rendering the page we eventually see.

import { createApp } from 'vue'
import App from './App.vue'

import './assets/main.css'

createApp(App).mount('#app')

The first two lines import two variables from the ‘vue’ library called createApp and create an App object from ‘./App.vue’ template. Then the third import is just pulling in the main.css file. The fourth line uses the createApp operatig on the App object to .mount the application at the point of the #app anchor in the template App.vue. That leads to needing to take a look at App.vue to see what exactly the vue app is mounted to.

NOTE: I’m not 100% sure I’m describing this as precisely as I should, as the blog entry details, this is day 4 of Vue.js studies. I’d started in the past once or twice, and have done a ton of web dev over the years, but Vue.js is largely new to me. So if you see something worded incorrectly or oddly, please comment with questions or corrections.

App.vue

The App.vue file for the WebStorm generation seems to have a bit more from the other apps generated from other tooling. Whatever the case, let’s pick this apart and learn what is which and which is what in this file.

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />
    </div>
  </header>

  <main>
    <TheWelcome />
  </main>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>

Right at the beginning of the App.vue file there is a <script setup></script> section that imports two other components that are located in the components directory that the App.vue file is located in. This is the HellowWorld.vue and TheWelcome.vue components. There is a third component, the WelcomeItem.vue component, in the component directory along with an icons directory.

With all of these assets now ready, clicking on the play or debug buttons in WebStorm will issue to the command to execute and display the app in the default browser. I’ll cover more of the assets as we get to each of them, for now I’m going to move along and get into some components and all.

When the IDE (or you do manually) launches the browser to display the app it will look like this.

Checkpoint: Vue App Operational

This is a good time to checkpoint. If you’ve been following along and everything is as shown above, we’re good to move along to the next steps. If not, then something is amiss, probably broken, and that needs resolved first. If you’ve run into a problem at this point, leave a comment with a description of the issue and I’ll endeavor to help you resolve the problem. Otherwise, moving along to some edits and checking out Vue.js’s features and capabilities.

Once the next post is live, I’ll add the link here to that post… it’s coming soon!

Day 5 Studies – Linked Lists 😱

I needed a refresher, as I’m at the point in my career I tend to just implement the things and not remember what they’re called anymore. Whether a refresher or you’re new to coding, maybe my refresher will be a good stroll through linked lists.

First off, what exactly is a linked list? The name sort of defines what we’re talking about, but a definition would definitely help. From an actual dictionary, I dug up the following definition.

“A simple linear data structure, each of whose nodes includes a pointer to the next (and sometimes previous) node in the list, enabling traversal of the structure in at least one direction from any starting point.”

via Wordnick

The parenthesis above overloads the definition a bit in describing both a simple linked list and a doubly linked list. Let’s define further to differentiate those two and throw in a circular one to boot.

Singly Linked Lists

Each node contains a pointer to the next node. The code for a singly linked list would look something like this, if you put it together in JavaScript.

class ListNode {
    constructor(data) {
        this.data = data
        this.next = null
    }
}

class LinkedList {
    constructor(head = null) {
        this.head = head
    }
}

Note however, in this example, the pointer is really the next inferred object. You’d need to use a language like C, or C++, to build a linked list with an actual pointer. that would look something like this.

struct Node {
    int data;
    struct Node* next;
};

#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
};
 
void printList(Node* n)
{
    while (n != NULL) {
        cout << n->data << " ";
        n = n->next;
    }
}

Here you can see the * used to set a pointer and then the reference to move between the nodes below. It’s a bit more complicated using a language like this, but I wanted to – because I’m often complicated – point out how it would be done with C++. This introduces additional capabilities, but I won’t go on about the nuances of using actual pointers here and am instead going to focus on the linked list concepts themselves. However it doesn’t hurt to know this and along with pointers themselves, this is a great topic for another post another time, so back to linked lists!

Referring back to the JavaScript example above, if you were to build out several nodes like this.

let node1 = new ListNode("a singular node.")
let node2 = new ListNode("some other node.")
let node3 = new ListNode("and another rando node.")

Then put together the nodes, and instantiate a linked list like this.

node1.next = node2
node2.next = node3

let list = new LinkedList(node1)

You can then request various nodes of the linked list or get the linked list object itself like this.

console.log(list.head)  
console.log(list.head.next.data)
console.log(list.head.next.next.data)

The first console log would print out the entire list.head object, which means all of the nested objects too. That would look like this.

ListNode {
  data: 'a singular node.',
  next: ListNode {
    data: 'some other node.',
    next: ListNode { data: 'and another rando node.', next: null }
  }
}

The second and third console logs would print out "some other node." and "and another rando node." respectively.

Double Linked Lists

Each node contains a pointer to the next and previous nodes. That turns the above example into this.

class ListNode {
    constructor(data) {
        this.data = data
        this.next = null
        this.prev = null
    }
}

class LinkedList {
    constructor(head = null) {
        this.head = head
    }
}

Summary

That’s the short SITREP on LinkedLists. There’s a lot more to cover, the functions that work on the list, the traversals, the addition and removal of nodes, etc. But this post is just intended for a quick review of the structure of linked lists at their core. On to next topics, cheers!

Day 4 Studies – Web Related Things

Today I got into some studying Vue.js, but realized I wanted to cover some of the basics around things that Vue.js uses but I’d not really covered in the posts. Also before I got into some of the other core topics as outlined on Day 1 there were a number of things that just needed defined. This post, is about those things.

Virtual DOM – this is something you hear about that isn’t specifically Vue.js related. React uses a virtual DOM as do other frameworks. The DOM part stands for Document Object Model, and the Virtual DOM is a lightweight JavaScript representation of this model. This Virtual DOM is what is updated instead of the actual DOM, and when the Virtual DOM is ready for rendering to the actual DOM, a diff is done of the two and only the changes are rendered in the actual DOM. This generally makes changes render much faster than attempting to make the changes in the actual DOM only.

The frameworks that use a Virtual DOM include; React, Vue.js, and Elm. Other frameworks like Svelte created by Rich Harris does not, and Rich is also quoted as saying a Virtual DOM is pure overhead. A valid point, yet arguable whether this is an advantage or disadvantage, as it appears to depend entirely on the situation and type of page(s) being rendered.

There are other techniques like Angular or Ember.js’s incremental DOM that offer an alternate approach to DOM rendering.

Digging more closely into the Document Object Model, it is a cross-platform language independent interface that uses a tree structure to represent XML or HTML. Each branch of the DOM ends in a node, each node containing objects. This provides a way to programmatically traverse the model and gain access to various parts of the tree. The nodes within the DOM can also have event handlers attached to them, which provides a programmatic way to fire off events for execution.

The DOM technology is currently managed by WHATWG – Web Hypertext Application Technology Working Group.


Rendering Mechanism – This is the way, process, and flow of Vue.js’s rendering of a page for a Vue Application.

This all starts in Vue.js, with the above defined Virtual DOM, as defined in the docs as the VDOM. Remembering from above, that each branch ends in a node, a constant of the VDOM could be written up as shown.

const vnode = {
  type: 'div',
  props: {
    id: 'anIdentifierOfSorts'
  },
  children: [
    /* all the other nodes on down the tree. */
  ]
}

The Render Pipeline, at a high level compiles, mounts, and patches the VDOM. Vue templates are compiled into render functions that return VDOM trees. The mount function then invokes the render function which walks the returned virtual DOM tree, creates actual DOM nodes based on it and renders. This is performed as a reactive effect to apply changes to the actual DOM. Finally during mount changes, the effect reruns during patch, which creates a new VDOM, the runtime renderer walks the tree, does a diff, and applies updates to the actual DOM.


Templates & Render Functions

It’s important to know that Vue templates are compiled into VDOM render functions. Render functions can also be authored and called programmatically, bypassing a need to create a template. Even though vue recommends, and many if not most tutorials will show templates versus render functions, it’s important to know that render functions are available to use for more flexibility when dealing with dynamic logic or just odd business rules and such.

Vue.js Studies Day 3 – More Ways to Get Started

Method 3 – JetBrains WebStorm

For this next method on getting started I decided to give JetBrains WebStorm a go and see what it used, and what extras it would provide. I presumed correctly, that there is indeed lagniappe!

I opened up WebStorm – to note, I’ve got a full subscription to the entire line of JetBrains tools but you can go get a free trial version if you want to give it a try – and clicked on the File menu and New, then on Project.

That brings up another window with project and I clicked on New Project from there, which gives me a list of web projects to start and I chose Vue.js. After entering location and node interpreter, the Vue CLI – both of which I’ve already got installed but if they’re not, WebStorm can do that for you – and then click Create.

That’ll spin up a project and open it in the IDE itself. You’ll see a prompt popup that’ll ask if you want to run npm install and if not, be sure to run that either view the embedded CLI, or via the run npm option in the IDE. The IDE’s display will show the familiar “Process finished with exit code 0”.

Now there are a range of ways to run the application that was just generated for us. To note, WebStorm has used the same method that you can use if you execute npx create-vue. The big differences are there are now hooks, and the IDE itself is aware of a number of things that can help you do a number of things from debugging to application execution. For example, looking up at the top of the IDE (pending it’s a default install and you’ve not moved parts of the IDE around!) we now have a button to execute the application with npm, or to execute and debug the application.

When you execute the application, the window at the bottom of the IDE will pop up with the familiar launch of vite, and you can even click on the local URI and it’ll launch your default browser. You can also setup the IDE to, by default, launch the browser if you’d like.

Vue.js Studies Day 2 – Getting Started/Installed/Creating an App

I’m going to enumerate these, because holy hell there’s a number of ways to start working with Vue.js. Since I’m time boxing all of the these posts too and study time in a day, it might take more than one post to get through all of these ways to get started with Vue.js.

Method 1 – Hand Crafted Artisanal Vue App

This is the age old approach, and in my opinion one of the best ways to learn something well, to just hand code up a minimal app from scratch. Doing this with Vue is fairly easy, and as with any web application regardless of framework, begins with two files. For these files, we have:

  1. index.html – The index.html file is the standard base file of a web app, or more simply the web site. It’s been the default file that displays for a website since pretty much the dawn of the internet using HTML for composing sites!
  2. main.js – This is the part that initiates the Vue app itself.

Creating the index.html we would need something like this. Note the script file is located on a CDN, and works fine until you don’t have access to the internet (if that were to happen). It’s possible to do the same thing locally by just downloading the vue.js vue.global.js file locally.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Minimalistic Vue App</title>
    <script src="https://unpkg.com/vue@3.0.0-beta.12/dist/vue.global.js"></script>
  </head>
  <body>
    <div id="app">
      <h1>{{ appHeader }}</h1>
      <p>{{ appDescription }}</p>
    </div>
    <script src="./main.js"></script>
    <script>
      const mountedApp = app.mount('#app')
    </script>
  </body>
</html>

The JavaScript page, where the invocation of the Vue app is done is loaded via the <script src="./main.js"></script> file, while the Vue framework itself is loaded by the <script src="https://unpkg.com/vue@3.0.0-beta.12/dist/vue.global.js"></script> in the header. Then the app is attached the the div element <dev id="app"> and the elements inside then have various pieces that the Vue framework can then populate based on the capabilities of the framework.

The underlying main.js file looks like this.

const app = Vue.createApp({
    data() {
        return {
            appHeader: 'This is yer Header!',
            appDescription: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
        }
    }
})
The page displayed.

Method 2 – Creating a Project via NPM

To use this method start by ensuring you have Node.js and npm installed. I use nvm to get these tools installed and manage which version of these tools I have installed, and have detailed what steps I go through here.

Once the prerequisites are installed issue the following npm init command.

npm init vue@latest

That’s it, next you’ll be prompted for all sorts of additional capabilities one can add to a Vue.js App. The easiest however is just to ignore them all, go with the default of No, and then navigate into the directory made for you, install dependencies, and run the app with the following commands. Which mind you, are listed out when you run the above npm init. Working through this automation your terminal would look something like this.

Working through the npm init in the terminal.

Once all that is done, you then npm install and then issue npm run dev you’ll be presented with the following status.

Vite is now running with the default app.

This shows that your app is now running and available via a VITE server that you can open a browser and navigate to http://localhost:5173 to view. That page will look something like this, which is a smidge more shined than a hand crafted artisanal vue app!

A default vue app when using npm init vue@latest.

That’s it for today’s notes. I spent an exorbitant amount of time toying around with these things so I’ve only gotten through the two methods. But rest assured, these are effective ways to get your vue app started and get going with that initial development.