₦airaland Forum

Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,259,172 members, 4,942,476 topics. Date: Saturday, 25 May 2019 at 04:51 AM

Discovery Vue Journal - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Discovery Vue Journal (276 Views)

Abuja Laravel, Vue, Phonegap Programmer Desperate For A Job / Learn How To Build A Realtime Chat Application With Django, Rabbitmq And Vue.js / Learn Vue Js 2 (2) (3) (4)

(1) (Reply) (Go Down)

Discovery Vue Journal by Lemeechi: 2:43pm On May 08
1904151

Getting Started!


This is all about my journey into VueJS, learning Vue and using Vue. Prior to my reading about JavaScript frameworks early in the year, starting with React, I used to see mentions of Vue without paying attention. Then on March 14, I read about React at Wikipedia, along with a smaller framework called Riot, and then saw that Evan You that created Vue used to work for Google that created AngularJS, using Angular, and he wanted Vue to have the best of the features he liked in Angular. This fed my curiosity.

On this day, April 15, I began really exploring VueJS, reading the little about it at W3Schools.com then more at their own vuejs.org site, going through a 5-minute getting-started tutorial there although the sample application demonstrated didn't completely work when I coded it.

What is VueJS?

VueJS is a JavaScript framework that extends HTML with new attributes and directives, and like AngularJS is perfect for Single Page Applications (SPAs).

To use VueJS:

1. Include the Vue JavaScript file (web-based or on local disk) in a <script> tag within the <header> tag of HTML document, such as:

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

2. Bind VueJS object to HTML elements and use double braces to represent VueJS data:

<div id="app">
<h1>{{ message }}</h1>
</div>
...
<script>
var myObject = new Vue({
el: '#app',
data: {message: 'Hello Vue!'}
})
</script>

After a VueJS object is bound to an HTML, changing the VueJS variable (such as myObject.message) also changes the HTML (the <h1> value). While double braces show the value of expressions, another binding method is the v-model directive which binds input HTML elements to variables, such that when the input values change the variable values also change:

<div id="app">
<p>{{ message }}</p>
<p><input v-model="message"></p>
</div>

In this case any value typed into the text box appears in the paragraph above it.

The v-for directive binds an array of Vue values to an "array" of HTML elements.

<div id="app">
<ul>
<li v-for="x in todos">{{ x.text }}</li>
</ul>
</div>
...
<script>
myObject = new Vue({
el: '#app',
data: {
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue.js' }
]
}
})
</script>


Installing Vue
For a basic installation, the development version (https://vuejs.org/js/vue.js) includes warnings while the production version (https://vuejs.org/js/vue.min.js) does not. Once included with the <script> tag, Vue will be registered as a global object. Also Vue DevTools facilitates application debugging, https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/ for Firefox and https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd for Chrome.
Re: Discovery Vue Journal by Lemeechi: 7:59am On May 12
For some unknown reasons the second post above got hidden. But you can see a much better-looking version here.
Re: Discovery Vue Journal by Lemeechi: 12:26am On May 16
1904173

The Vue Mastery introductory course, Part 1


Having finished with the getting started video at vuejs.org, I began the next exploration with the free Vue Mastery introductory course containing 11 lessons, each a downloadable video. In this first part of the post I will summarize the first seven lessons.

Lesson 1 - Vue instance
This showed how the Vue object was declared, with the el element pointing to the HTML container where Vue will be put to work. Discussed Vue expressions and its reactivity feature, which means when a Vue variable changes value, the new value will automatically appear wherever the variable is referenced in the HTML, and vice versa, just like with AngularJS. The following are examples of Vue expressions.

{{product}}
{{product+'?'}}
{{firstName+' '+lastName}}
{{clicked ? true : false}}
{{message.split(' ').reverse().join(' ')}}


Lesson 2 - Attribute binding
<img v-bind:src="image"> The HTML attribute src is here bound to the Vue expression consisting of the variable image: When the variable changes, the HTML attribute will also change. “v-bind” can be omitted, leaving just the colon, so v-bind:src is the same as :src. Examples of other HTML attributes that can be bound are alt, href, title, class, style, disabled.

Lesson 3 - Conditional rendering
<p v-if="inStock"> Renders the p element if variable inStock has a value of true.
<p v-if="onhand>10"> Here a logical expression is used instead.
<p v-else-if="onhand<=10&&onhand>0"> If the former expression is false this one is evaluated next.
<p v-else> If prior expressions are false this one is taken.
In all these the p element will be created in the DOM if the expression is true, deleted from the DOM if false. v-show is similar except the element is just hidden or shown rather than being deleted or created.

Lesson 4 - List rendering
<li v-for="detail in details">{{detail}}</li>
<p v-for="variant in variants" :key="variant.variantID">{{variant.variantColor}}</p>

The v-for directive renders lists. From the way it works, it appears to duplicate the HTML element where it’s specified as many times as the contents of an array. The array is represented as the second variable after in while the one before in represents the current array cell value.

Lesson 5 - Handling events
v-on:click="addToCart" v-on: which may be abbreviated to @ binds an expression to an event, in this case the button click event. The expression can be something like cart+=1 or a method call as in this case. For method calls, parentheses are only necessary when arguments are being passed. Examples of other events are mouseover, submit (for a form), keyup.enter (for an input box, the .enter being a modifier specifying that Enter key is required). The methods are defined using the methods attribute of the Vue instance:

methods:{
addToCart(){this.cart+=1},
updateProduct(image){this.image=image}
}


Lesson 6 - Class and style binding
Style binding
Styles can be bound collectively using a Vue object variable, or individually. For instance in <span :style="boxStyle">...</span> the variable boxStyle would have been created as an object as in boxStyle: {backgroundColor:"red", color:"white"} Here, the color properties are either camel-cased or quoted when not, and comma is used for separation instead of semicolon. When there are more than one variables to be bound, an array is used as in :style="[boxStyle, textStyle]" Here is an example of binding the style individually: <span :style="{backgroundColor:'red'}"> The constant 'red' could also be represented by a Vue variable which would not be quoted. Vue expressions need to be quoted only when being assigned or bound to HTML attributes.

Class binding
Vue class binding adds a class when an expression evaluates to true.

:class="{disabledButton: !inStock}"
Will add the disabledButton class when !inStock evaluates to true.

:class="{active: activeClass, 'text-danger': errorClass}"
'active' class will be added when activeClass value is true and 'text-danger' will be added when errorClass value is true.

:class="classVar"
classVar is an object variable, whose value could be {active: true, 'text-danger': false}

:class="[classVar1,classVar2]"
Binding to multiple class object variables at once.

:class="[ isActive ? 'active': 'inactive']"
Will add the 'active' class when isActive evaluates to true, or else the 'inactive' will be added.


Lesson 7 - Computed properties
computed is an object attribute of the Vue instance consisting of functions that compute and return values. The computed values are cached until any dependent variable changes, so are more efficient than using methods for the same purpose. Although they are functions, to use them in expressions the parentheses are optional unless when arguments are needed. For example:

computed:{
title(){return this.brand+' '+this.product},
image(){return this.variants[this.selectedVariant].variantImage},
}

By the conclusion of this lesson, the course application now looks like this.


And the Vue instance declaration looked like this:

var app=new Vue({
el: '#app',
data: {
brand:'Vue Mastery',
product:'Socks',
selectedVariant:0,
details: ['80% cotton','20% polyester','Gender-neutral'],
variants: [
{variantID: 2234, variantColor: 'green', variantImage: '../vmSocks-green-onWhite.jpg', variantQuantity:10},
{variantID: 2235, variantColor: 'blue', variantImage: '../vmSocks-blue-onWhite.jpg', variantQuantity:0}
],
cart: 0
},
methods:{
addToCart(){this.cart+=1},
updateProduct(variantIndex){this.selectedVariant=variantIndex}
},
computed:{
title(){return this.brand+' '+this.product},
image(){return this.variants[this.selectedVariant].variantImage},
inStock(){return this.variants[this.selectedVariant].variantQuantity}
}
})
Re: Discovery Vue Journal by Lemeechi: 11:51pm On May 17
1904195

The Vue Mastery introductory course, Part 2


Having finished with the getting started video at vuejs.org, I began the next exploration with the free Vue Mastery introductory course containing 11 lessons, each a downloadable video. In the earlier post I summarized the first seven lessons. This is the concluding part where I summarize the last four lessons.

Lesson 8 - Components
The lesson transformed the product div portion of the application (and applicable sections of the Vue instance declaration) to a component so that it got replaced with <product :premium="premium"></product> in the HTML just like it’s done in React. Unlike in React, components are not created as classes. The following shows the structure of a component:
Vue.component("componentID",{
props: propsDefinition,
template: templateDefinition,
data(){ return dataObject },
methods: methodsObject,
computed: computedObject
})

The componentID can be any value not containing space apart from a built-in HTML attribute. It is what will be placed inside <> to render the component. The propsDefinition is an object containing one or more variables such as {premium:{type: Boolean, required: true } } and defines the arguments to be passed to the component, in this case one named premium. The template property is the only compulsory one in the component options object. It is the one that defines the HTML string to be rendered by the component. Its one requirement is only one root-level HTML element can be returned. This means "<p>First paragraph</p><p>Second paragraph</p>" can’t be returned because there are two <p> elements, so the solution would be to put them in a container, as in "<div><p>First paragraph</p><p>Second paragraph</p></div>" and now there is only one root <div> being returned. There are different methods of creating a template such as multi-line string or single-line string, quoted with back-tick, or single- or double-quote characters as the need may be. This Medium article listed seven methods. The dataObject, methodsObject and computedObject values are just like in the Vue instance declaration.

Lesson 9 - Communicating events
When a component needs to let the parent know of an event within it, it needs to $emit the event like this: this.$emit("customeventname",eventparam) At the point the component is called, the event will need to be listened for like this: <Component @customeventname="handler"> Here, handler could be a method and if the event would be emitted with the optional eventparam then the method would be declared with an argument.

Lesson 10 - Forms
A product-review component was added to the app, within the product component, with the following form features:

1. @submit.prevent="onSubmit" The .prevent modifier stops the default behavior of page re-display when the form is submitted. The onSubmit method collects the values on the form into an object and then emits a review-submitted event with it. The event handler adds the data to an array for the product component, which is then listed out in a “Reviews” section before the reviews form. onSubmit also handles custom validation, checking to see that each field was supplied.

2. v-model="review" Each HTML input element is bound to a Vue variable with v-model so that a change in the input would reflect in the variable (review in this case) and vice versa. v-model.number ensures that the returned value is a number, and also introduces increment/decrement arrow buttons for a text input box.

3. Custom error display. The required attribute for HTML input elements was bypassed. An errors array was added to the data object of the component and is populated by the onSubmit method. At the top of the reviews form if the array is not empty its contents are displayed.

Lesson 11 - Tabs
A product-tabs component was added to the app, within the product component, while the product-reviews component was moved from product to it. It’s basically a menu bar inside a div with two options “Reviews” and “Make a Review” followed by two elements, one for each menu item, only one showing at a time (via v-show), the one corresponding to the currently-selected menu item. The reviews array declared for the product component now had to be passed to the product-tabs as an argument. But the addReview() method of the product component no longer worked as product no longer referenced the product-reviews directly. My first solution was to just transfer it from the product component to product-tabs and this worked, probably because arrays were passed as arguments by reference, and values in a component’s props can also be prefixed with this just like data values.

However, the lesson author’s solution turned out to be different as he said a grandchild cannot emit an event for a grandparent to listen to. What he did was to

1. Remove the listening for the review-submitted event from where product-reviews was called within product-tabs.

2. Declare a new global Vue instance called eventBus with no parameters:
var eventBus=new Vue()

3. Use eventBus within the onSubmit method of the product-reviews component, to emit the event, rather than using this:
eventBus.$emit("review-submitted",productReview)

4. Remove the addReview method from product component.

5. Introduce the mounted() lifecycle method for the product component, which now used eventBus to listen to the review-submitted event and then do exactly what addReview() used to do:
mounted(){
eventBus.$on("review-submitted",productReview=>{this.reviews.push(productReview)})
}


By the conclusion of this lesson, and the Vue Mastery introductory course, the course application now looks like this.


And the Vue instance declaration looked like this, with most of the code from the end of lesson 7 having been moved out to components:
var app=new Vue({
el: "#app",
data:{premium:true, cart: [] },
methods:{updateCart(id){this.cart.push(id)} }
})
Re: Discovery Vue Journal by Lemeechi: 9:13pm On May 23
1904210

The Vue JS crash course by Traversy


Brad Traversy is one of the popular web development authors on YouTube. My next trip on the VueJS journey was to go through his Vue JS Crash Course – 2019 video.

1. Introduction

Brad starts off by introducing VueJS and its offerings. Among the tools, I took note of Vue CLI 3 and Vuex. Vue CLI 3 is a tool for generating and building VueJS apps. It incorporates Babel (“compiles” code to browser-compatible JavaScript), TypeScript, ESLint, PostCSS and others. It includes a development server with hot reload, and a tool to manage an app in a GUI. Vuex is used to manage application state across different components, similar to Redux and Flux. It serves as a central store for all components, eliminating the need for passing state details as component parameters or props. It uses actions to update the global state which then gets sent down to components. It is very ideal for large applications. As the application to be created for the course was small, Vuex would not be used.

2. Installing Vue CLI

The documentation for CLI is found at its website. CLI is a Node.js module and the latest version 3 is named @vue/cli. To install it the following is typed at the command prompt: npm i -g @vue/cli

After installation, there are two ways to create a new app, typing vue create appname or vue ui. In the first case, directory or folder appname will be created with template and library files and inside it, typing npm run serve will start the development server with the application on port 8080.


In the second case, the development server is started on port 8000 and Vue Project Manager opens against it on the browser, with options to create, list or import a project. Choose to create and then you specify the project name and some options like presets. (Saved presets will be stored in a JSON file named .vuerc in your user home directory. If there is need to modify saved presets or options, this can also be done by editing this file.) It takes a while to install CLI plugins, additional dependencies, and after almost 20 minutes (on a 1.65 GHz laptop with Windows Experience Index 3.9), it announces success and opens the Project dashboard window. (On checking the node_modules directory I saw 802 subdirectories or modules downloaded and installed, no wonder it took so long, including express module that I previously installed globally.) It’s definitely an overkill when the project is very small and just a couple of files would do, for HTML and JavaScript code.

The newly-created project directory contained the following:

1. Three subdirectories: node_modules, public, src: The application files are in public (index.html and favicon.ico) and src (assets\, components\, main.js, App.vue). src\assets contains logo.png (the Vue logo) while src\components contains HelloWorld.vue. The .vue extension is for component files containing <template>, <script> and optional <style> sections.

2. Five files: README.md, package-lock.json, package.json, .gitignore, babel.config.js

3. GitHub registration and tutorial

While looking for a Sublime Text syntax highlighting package for .vue files I ended up at GitHub where I saw one. I read a Medium article earlier today about working with GitHub (Getting started with Git and GitHub: the complete beginner’s guide), so I decided to register my account and then went through the introductory “Hello World” tutorial:

1. Create and use a repository named hello_world

2. Start and manage a new branch: With the master branch being the original, other branches are temporary copies for modifications.

3. Make changes to a file (README.md) and push them to GitHub as commits.

4. Open and merge a pull request: Pull requests compare changes in a branch with another, for others to comment on or for you to see. Merging makes the changes permanent, after which the branch can be deleted.

I did find a .vue file syntax highlighter that is now effective in Sublime Text. Preferences > Package Control > Package Control: Install Package lists out the packages from a web repository and I could type vue to filter the results. I first selected Vue Syntax Highlight package that I saw at GitHub via Google search, but it didn’t alter the presentation of my already open .vue file. I then installed Vuejs Complete Package and it did. I also installed Babel package for JSX formatting, though I noticed that for it to be fully effective, the default JavaScript package may need to be disabled first.

4. Vue-Router

This was installed midway into the course. It allows each route to render a different component. Installing it from the Vue Package Manager has one side effect, the App.vue file is overwritten so it had to be backed up first. Along with modifying App.vue to now have two sample routes (/ and /about) to display Home and About components that it creates, the installer also creates src\main.js and src\router.js files, and a views subdirectory with the Home.vue and About.vue component files.

The new Home.vue was then replaced with the former App.vue contents. The location of the components directory within it, and the component’s name, were adjusted.

5. Run build

The build option in the Vue Package Manager “compiles” and minifies files for production use within a dist subdirectory. The first build attempt failed with errors after 320 seconds: axios dependency not found. I had to run npm install --save axios before it succeeded. What the build process does is to convert most of the VueJS and HTML into JavaScript code with all the unnecessary spacing and line breaks taken out.

6. Course summary

The course work for Traversy’s VueJS Crash Course - 2019 is the implementation of a to-do list application similar to the one for the React course I went through before. Unlike the Vue Mastery intro course this one briefly covered installing and using the CLI (that works just like React with the exception of its browser-based GUI tool, the Vue Package Manager) and also implemented HTTP calls via axios module and routing via the vue-router, along with covering the following methods and directives: $emit(), created(), v-bind, v-on (also @), v-model, v-for, scoped (styles), <template>, <router-link>, <router-view>. While several Vue.component() methods were used in the Vue Mastery course to define components in the same script file, here each component is a separate .vue file, just like in React (where they are separate .js files). Each .vue file had three sections, <template> for the HTML, <script> for the component definition and <style> for the component’s CSS, the scoped attribute allowing for a component-only style sheet. Only the first section is compulsory. A simplified props syntax was used, listing the variables in an array without any details, while in the VM course a more detailed object syntax was used. It dealt with the same issue of communicating an event from a grandchild component to a grandparent in a different manner, by having the parent also emit the same event as the grandchild did, instead of using an event bus.

(1) (Reply)

Learn Programming For Free In Sokoto / Subsidized Web Programming & Security Training / Learn Basic Computer Programming And Networking With Brothers Tech

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (0) (1) (2) (3) (4) (5) (6) (7) (8) (9)

Nairaland - Copyright © 2005 - 2019 Oluwaseun Osewa. All rights reserved. See How To Advertise. 248
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.