0% found this document useful (0 votes)
12 views

Vue Notes 1

The document provides a comprehensive overview of Vue.js, a front-end framework for building JavaScript-driven web applications with high performance and a lean production version. It covers installation methods, the creation of Vue instances, data binding, event handling, computed properties, and the use of components, including props and event buses for communication between components. Additionally, it includes examples and references for further learning and practical applications of Vue.js.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Vue Notes 1

The document provides a comprehensive overview of Vue.js, a front-end framework for building JavaScript-driven web applications with high performance and a lean production version. It covers installation methods, the creation of Vue instances, data binding, event handling, computed properties, and the use of components, including props and event buses for communication between components. Additionally, it includes examples and references for further learning and practical applications of Vue.js.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

Vue.

js

Introduction to Vue.js
●​ A front-end framework
●​ Create JavaScript drive web applications
●​ Runs in the browser
●​ No need to make multiple server requests for pages
●​ Very lean production version (16kb)
●​ Very high run-time performance

Installing Vue.js

How to Install Vue.js the easy way using CDN (Content Delivery Network):
●​ Conditionals
●​ Events
●​ Data

How to Install Vue.js with the vue-cli and webpack:


●​ Components
●​ Vue files and templates

*** Installing Vue.js with the vue-cli and webpack is typically used for larger files.
*** Get Vue on (https://vuejs.org/v2/guide/)
*** In talking about JavaScript, "instance" can be used informally to mean an
object created using a particular constructor function.
*** Repository of the Sample Vue.js Code in the tutorial:
https://github.com/iamshaunjp/vuejs-playlist
https://github.com/iamshaunjp/vuejs-playlist/blob
Figure 1.0 - Installation of Vue.js the Easy Way through CDN

Figure 1.1 - [email protected] Version

The Vue Instance


●​ A new Vue object is created with new Vue()
●​ The property el: binds the new Vue object to the HTML element with id="app"
●​ Consist of different key value pairs
●​ Vue.js uses double braces {{ }} as placeholders or template for data
●​ To Control certain part or all of application and storing different things within that
Vue or to control a certain template

Figure 1.0 - New Vue Object with El and Data Property

Input:
Figure 1.1 - Sample Vue Instance #1

Figure 1.2 - Sample Vue Instance #2

Output:
Figure 1.3 - Sample Vue Instance #3

Data & Methods


●​ Different methods can be stored within Vue instance

Input:
Figure 1.0 - Sample Vue Instance with Method #1

Figure 1.1 - Sample Vue Instance with Method #2

Output:
Figure 1.2 - Sample Vue Instance with Method #3

Data Binding
●​ Bind dynamic data to HTML elements
●​ Use of v-bind: directive to bind dynamic data that was stored on view instance
●​ The @ character can be used as shorthand for the v-on: directive
●​ V-bind can be used to different HTML attributes

Input:
Figure 1.0 - Use of V-bind Directive on Href and Value #1

Figure 1.1 - Use of V-bind Directive on Href and Value #2


Output:

Figure 1.2 - Use of V-bind Directive on Href and Value #3

Input:
Figure 1.3 - Property containing HTML Tag #1

Output:

Figure 1.4 - Property containing HTML Tag #2

Events
●​ The v-on: directive is used to create HTML events

Input:

Figure 1.0 - V-on:click Directive #1


Figure 1.1 - V-on:click Directive #2

Output:

Figure 1.2 - V-on:click Directive #3


Input:

Figure 1.3 - V-on:dblclick Directive #1

Figure 1.4 - V-on:dblclick Directive #2


Output:

Figure 1.5 - V-on:dblclick Directive #3

Input:
Figure 1.6 - V-on:mousemove Directive #1

Figure 1.7 - V-on:mousemove Directive #2


Figure 1.8 - V-on:mousemove Directive #3

Output:

Figure 1.9 - V-on:mousemove Directive #4

Event Modifiers
●​ DOM event handlers can have modifiers that alter their behaviour.
●​ Types of Event Modifiers: once, prevent, stop, capture, self, passive
●​ For example, an event with once modifier will execute a function only once
Figure 1.9 - Once Event Modifier

Keyboard Events
●​ Three types of keyboard events:
○​ Keydown - Keydown happens when the key is pressed down, and auto
repeats if the key is pressed down for long.
○​ Keypress - This event is fired when an alphabetic, numeric, or
punctuation key is pressed down.
○​ Keyup - Keyup happens when the key is released
●​ Key Modifiers: enter, tab, delete, esc, space, up, down, left, right

Input:
Figure 1.0 - Keyup Event with Alt and Enter Key Modifiers #1

Figure 1.1 - Keyup Event with Alt and Enter Key Modifiers #2

Output:
Figure 1.2 - Keyup Event with Alt and Enter Key Modifiers #3

Two-Way Data Binding


●​ The v-model is a directive that provides two-way data binding between an input
and form data or between two components.

Input:
Figure 1.0 - V-model Sample #1

Figure 1.1 - V-model Sample #2

Output:

Figure 1.2 - V-model Sample #3


Computed Properties
●​ Computed properties enable to run functions that are needed unlike methods
which run functions simultaneously.

Input:​ ​ ​ ​

Figure 1.0 - Method Sample #1


Figure 1.1 - Method Sample #2

Output:​

Figure 1.2 - Method Sample #3


Input:​

Figure 1.3 - Application of Computed Properties #1


Figure 1.4 - Application of Computed Properties #2

Output:

Figure 1.5 - Application of Computed Properties #3


Dynamic CSS Classes
●​ Vue enables to dynamically toggle classes

Input:​
Figure 1.0 - Dynamic CSS Class #1

Figure 1.1 - Dynamic CSS Class #2


Figure 1.2 - Dynamic CSS Class #3

Output:​

Figure 1.3 - Dynamic CSS Class #4


Conditionals
●​ The directive v-if is used to conditionally render a block. The block will only be
rendered if the directive’s expression returns a truthy value.
●​ Another option for conditionally displaying an element is the v-show directive.
The difference is that an element with v-show will always be rendered and remain
in the DOM; v-show only toggles the display CSS property of the element.

Input:
Figure 1.0 - V-if Sample #1

Figure 1.1 - V-if Sample #2

Output:
Figure 1.2 - V-if Sample #3

Input:

Figure 1.2 - V-show Sample #1


Output:

Figure 1.2 - V-show Sample #2

Looping with V-for


●​ We can use the v-for directive to render a list of items based on an array. The
v-for directive requires a special syntax in the form of item in items, where
characters is the source data array and character is an alias for the array
element being iterated as shown on figure 1.0 below.

Input:
Figure 1.0 - Loop through Characters List using V-for #1

Figure 1.1 - Loop through Characters List using V-for #2

Output:
Figure 1.2 - Loop through Characters List using V-for #3

Input:

Figure 1.3 - Loop through Ninjas List using V-for #1

Output:
Figure 1.4 - Loop through Ninjas List using V-for #2

Input:

Figure 1.5 - Output Index #1

Output:
Figure 1.6 - Output Index #2

Figure 1.7 - Use of Template Tag to Eliminate Separate Divs


Input:

Figure 1.8 - Loop Through Key Value Pairs #1


Output:
Figure 1.9 - Loop Through Key Value Pairs #2

Simple Punch Bag Game


●​ Sample of a simple game using Vue.js
●​ Source:
https://www.youtube.com/watch?v=WjfpQlVem-8&list=PL4cUxeGkcC9gQcYgjhB
oeQH7wiAyZNrYa

Input:
Figure 1.0 - HTML Punch Bag Game #1
Figure 1.1 - CSS Punch Bag Game #2
Figure 1.2 - JS Punch Bag Game #3

Output:
Figure 1.2 - Punch Bag Game #4

Multiple Vue Instances


●​ Be able to control different sections of your website through multiple vue
instances
●​ For example, it can control different widgets on a website
●​ Store Vue instance in a variable

Input:
Figure 1.0 - HTML Vue Instance #1
Figure 1.1 - JS Vue Instance #2

Introduction to Components
●​ A component is a reusable piece of code or template that can be used in different
vue instances
●​ Define a new component using Vue.component() method
●​ When registering a component, it will always be given a name. For example, in
the global registration: Vue.component('my-component-name', { /* ... */ })
●​ The component’s name is the first argument of Vue.component
●​ There are two options when defining component names: kebab-case and
PascalCase
●​ When defining a component with PascalCase, you can use either case when
referencing its custom element. That means both <my-component-name> and
<MyComponentName> are acceptable. Note, however, that only kebab-case
names are valid directly in the DOM (i.e. non-string templates).
●​ The Vue.component() method takes two parameters. The first parameter is the
name of the component and the second parameter is an object.
●​ In Vue.component(), the data is not an object, rather, it must be a function.
Input:
Figure 1.0 - HTML Vue Component #1

Figure 1.1 -JS Vue Component #2


Output:

Figure 1.2 -Vue Component Output #3


Figure 1.4 -Vue Component Output #4

Refs
●​ Referencing with $refs
●​ Use refs to reach into the DOM and access information such as text input values,
inner HTML and more.
●​ Despite the existence of props and events, sometimes you might still need to
directly access a child component in JavaScript. To achieve this you can assign a
reference ID to the child component or HTML element using the ref attribute.
●​ Note: $refs are only populated after the component has been rendered. It is only
meant as an escape hatch for direct child manipulation - you should avoid
accessing $refs from within templates or computed properties.
●​ Props are custom attributes you can register on a component. When a value is
passed to a prop attribute, it becomes a property on that component instance. To
pass a title to our blog post component, we can include it in the list of props this
component accepts, using a prop option:

Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})

●​ A component can have as many props as you’d like and by default, any value
can be passed to any prop. In the template above, you’ll see that we can access
this value on the component instance, just like with data.
●​ Once a prop is registered, you can pass data to it as a custom attribute, like this:

Figure 1.0 -Prop

●​ In a typical app, however, you’ll likely have an array of posts in data:


Figure 1.1 - Array of Posts in Data

●​ Above, you’ll see that we can use v-bind to dynamically pass props. This is
especially useful when you don’t know the exact content you’re going to render
ahead of time, like when fetching posts from an API.

Input:

Figure 1.0 - Application of Ref #1


Figure 1.1 - Application of Ref #2

Output:

Figure 1.2 - Application of Ref #3


The Vue CLI
●​ Another way of setting up a Vue project using the Vue CLI
●​ CLI = Command Line Interface
●​ Create a dev environment workflow with webpack
○​ Use ES6 features
○​ Compile and minify JS into 1 file
○​ Use single file templates
○​ Compile everything on the machine, not in a browser
○​ Live reload dev server
●​ Install Node JS on the machine
●​ Source: https://github.com/vuejs/vue-cli/tree/master

Installation:
Figure 1.0 - Install Vue-CLI #1

Figure 1.1 - Install Vue-CLI #2

Figure 1.2 - Install Vue-CLI: List of Webpack Templates #3

Vue Files & The Root Component


●​ This single file component has 3 elements - a template, an object and some CSS
styles
●​ Images can be placed on assets folder

Figure 1.0 - Assets Folder

●​ The main.js file kicks when we run the application

Figure 1.1 - Main.js File with Root View Instance


●​ Babel - transpile ES6 code to Vanilla JavaScript
●​ Transpiling is a specific term for taking source code written in one language and
transforming into another language that has a similar level of abstraction.
●​ A source-to-source translator, source-to-source compiler, transcompiler, or transpiler is
a type of translator that takes the source code of a program written in a programming
language as its input and produces an equivalent source code in the same or a different
programming language.
●​ Use render method to render template in index.html.
●​ Figure 1.1 shows the root view instance which is controlling the app demo rendering the
root component
●​ A Vue file is just an extension of a component

Figure 1.2 - Sample of Parent Root Component


Figure 1.3 - Sample Vue File

Nesting & Importing Components


●​ Connect different components to the root component
●​ Two ways of registering components: globally or locally

Figure 1.0 - Nesting Components


Figure 1.1 - Registering Components Globally

Figure 1.2 - Nest Component with Output on Browser (Globally)


Figure 1.3 - New Component (Globally)

Figure 1.4 - Register Component (Locally)


Component CSS (Scoped)
●​ Style components independently of each other, using scoped styles.
Figure 1.0 - Style Scope Sample

Nesting Components Example


●​ Example of a simple web page by nesting multiple components into the root
component.

Figure 1.0 - Component Structure for this Project


Figure 1.1 - Root Component
Figure 1.2 - Footer Component
Figure 1.3 - Header Component
Figure 1.3 - Ninjas Component
Output:

Figure 1.4 - Nested Components Example Output


Props
●​ Props - a way to pass data from one component to another (parent to child).

Figure 1.0 - Props


Figure 1.0 - Root Component
Figure 1.1 - Ninja Component
Primitive vs Reference Types
●​ Primitive types are strings, booleans, and numbers
●​ Reference types are objects and arrays

Figure 1.0 - Footer Component


Figure 1.1 - Header Component
Figure 1.2 - Root Component
Events
●​ Use events to pass data from a child component to a parent component in
reaction to an event (such as a click event).
●​ Sometimes we also need to access the original DOM event in an inline statement
handler. You can pass it into a method using the special $event variable.
●​ $emit() function that allows you to pass custom events up the component tree.

Figure 1.0 - Change Title with Emit Function on Header Component


Figure 1.0 - Update Title on Root Component
Event Bus
●​ Create direct component to component data transfer using an event bus (which
is just a Vue instance which can emit and listen to events).
●​ Communicate between components without the parent
●​ Event bus is a Vue instance

Figure 1.0 - Event Bus Diagram


Figure 1.1 - Event Bus Created on Main.js

Figure 1.2 - Export Event Bus


Figure 1.2 - Emit Event from Header Component
Figure 1.3 - Listen Event from Header Component to Footer Component
Lifecycle Hooks
●​ Each component instance goes through a series of initialization steps when it's
created - for example, it needs to set up data observation, compile the template,
mount the instance to the DOM, and update the DOM when data changes. Along
the way, it also runs functions called lifecycle hooks, giving users the opportunity
to add their own code at specific stages.
Figure 1.0 - Lifecycle Diagram
Figure 1.1 - Lifecycle Hooks

Slots
●​ Vue implements a content distribution API that’s modeled after the current Web
Components spec draft, using the <slot> element to serve as distribution outlets
for content.
Figure 1.0 - Slot Sample on App.vue #1
Figure 1.1 - Slot Sample on formHelper.vue #2
Dynamic Components
●​ Using the 'component' tag Vue JS provides us with. Dynamic components allow
us to dynamically change which component is output to the browser.
●​ The is attribute to switch between components in a tabbed interface:

Figure 1.0 - Dynamic Components #1

●​ Recreating dynamic components is normally useful behavior, but in this case,


we’d really like those tab component instances to be cached once they’re created
for the first time. To solve this problem, we can wrap our dynamic component
with a <keep-alive> element:
Figure 1.1 - Dynamic Components #2
Figure 1.2 - App.vue
Figure 1.3 - formOne.vue
Figure 1.4 - formTwo.vue
Input Binding
●​ You can use the v-model directive to create two-way data bindings on form input,
textarea, and select elements. It automatically picks the correct way to update
the element based on the input type. Although a bit magical, v-model is
essentially syntax sugar for updating data on user input events, plus special care
for some edge cases.
●​ V-model internally uses different properties and emits different events for
different input elements:
○​ text and textarea elements use value property and input event
○​ checkboxes and radiobuttons use checked property and change event
○​ select fields use value as a prop and change as an event
●​ By default, v-model syncs the input with the data after each input event (with the
exception of IME composition, as stated above). You can add the lazy modifier to
instead sync after change events.
Figure 1.0 - App.vue
Figure 1.1 - addBlog.vue
Figure 1.2 - Output Blog using Input Binding
Checkbox Binding
●​ Use the v-model directive to bind data to checkboxes in our Vue forms.

Figure 1.0 - addBlog.vue


Figure 1.1 - App.vue
Figure 1.2 - addBlog.vue Style
Figure 1.3 - Output
Select Box Binding
●​ For radio, checkbox and select options, the v-model binding values are usually
static strings (or booleans for checkboxes).
●​ But sometimes, we may want to bind the value to a dynamic property on the Vue
instance. We can use v-bind to achieve that. In addition, using v-bind allows us
to bind the input value to non-string values.

Figure 1.0 - App.vue


Figure 1.1 - addBlog.vue
Figure 1.2 - Output Select Box Binding
HTTP Requests (POST Request)
●​ Vue Resource plug-in: https://github.com/pagekit/vue-resource
●​ Install, make, and handle HTTP requests with vue resource
●​ HTTP Requests - used for handling data like storing on database
●​ Vue.use(VueResource) - to put the plug-in into use and be able to use HTTP
requests
●​ $http.post - Post request which means grabbing the data that the users input to
the fields and post it somewhere like the database
●​ https://jsonplaceholder.typicode.com - fake JSON server used for sample
●​ A JavaScript Promise object contains both the producing code and calls to the
consuming code.

Figure 1.0 - Installation Vue Resource


Figure 1.1 - Installation Vue Resource Sample

Figure 1.2 - Import VueResource on main.js


Figure 1.3 - Promise Syntax
Figure 1.4 - App.vue
Figure 1.5 - addBlog.vue
Figure 1.6 - Output HTTP Request Post #1
Figure 1.7 - Output HTTP Request Post #2
GET Requests
●​ Get request ($http.get) - retrieve data and show that data
●​ this.$http.get('https://jsonplaceholder.typicode.com/posts') - fake domain rest API
●​ .then() function (or promise) only fires the function only when the this function
has been complete
●​ The slice() method returns selected elements in an array, as a new array.
Syntax: array.slice(start, end)

Figure 1.0 - App.vue


Figure 1.1 - showBlogs.vue
Figure 1.2 - Output Get Request
Custom Directives
●​ Make custom directives to implement custom behaviours in our applications.
●​ V-model, v-for, v-on, v-if are all examples of directives on Vue.js
●​ Global directive - any component can use it
●​ Create custom directive via Vue.directive()
Figure 1.0 - Main.js
Figure 1.1 - App.vue
Figure 1.2 - showBlogs.vue
Figure 1.3 - Output Custom Directive
Filters
●​ Change the output of our data on a browser by using custom filters
●​ Syntax: Vue.filter( id, [definition] )

Figure 1.0 - Main.js


Figure 1.1 - showBlogs.vue
Figure 1.1 - Output using Vue.filter
Custom Search Filter
●​ Create a custom search filter using computed properties.
●​ The match() method searches a string for a match against a regular expression,
and returns the matches, as an Array object.
●​ Syntax: string.match(regexp)

Figure 1.0 - showBlogs.vue


Figure 1.1 - Output using Custom Search Filter
Registering Things Locally
●​ Registering things locally using filters property.

Figure 1.0 - showBlogs.vue


Mixins
●​ Mixins are a flexible way to distribute reusable functionalities for Vue
components. A mixin object can contain any component options. When a
component uses a mixin, all options in the mixin will be “mixed” into the
component’s own options.
●​ Externalize the code from the components in a separate file so we don’t have to
write it twice

Figure 1.0 - searchMixin.js


Figure 1.1 - showBlogs.vue
Figure 1.2 - listBlogs.vue
Setting up Routing
●​ Dynamically show different components depending on which URL the user goes
to.
●​ Install third party package and save to our dependencies: ​ ​ ​ ​
npm install vue-router --save
●​ Vue.use(VueRouter) to put plug-in into use
●​ Register the routes in the new vue router instance
●​ The <router-view> component is a functional component that renders the
matched component for the given path. Components rendered in <router-view>
can also contain their own <router-view>, which will render components for
nested paths.
●​ Websites have different routes but we're not sending request to the server
we're not getting back muliple pages or reviews from the server, we're only
getting back the index.html but still we want to handle different routes with
Vue Js router which allows us to parse that URL and load different
components as pages.
●​ Empty path such as ‘/’ means default path
●​ Npm run dev
Figure 1.0 - routes.js
Figure 1.1 - main.js
Figure 1.2 - App.vue
Figure 1.3 - Setting Up Route

Figure 1.4 - Default Path


Hash vs History (Routing)
●​ Use the history routing mode instead of the hash mode for cleaner URLs.
●​ Hashes are used so it doesn’t have to keep making requests on the server
●​ For history routing, you need to set up the server so that no matter what you
put in after the forward slash, that way when it gets the index file, Vue js can run
in the browser and say ok I’m going to take care of the routing from this point so
whatever is placed after the forward slash I can deal with that.
●​ https://router.vuejs.org/guide/essentials/history-mode.html
●​ The default mode for vue-router is hash mode - it uses the URL hash to simulate
a full URL so that the page won't be reloaded when the URL changes.
●​ To get rid of the hash, we can use the router's history mode, which leverages the
history.pushState API to achieve URL navigation without a page reload.
●​ Here comes a problem, though: Since our app is a single page client side app,
without a proper server configuration, the users will get a 404 error if they access
http://oursite.com/user/id directly in their browser. Now that's ugly.
●​ Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback
route to your server. If the URL doesn't match any static assets, it should serve
the same index.html page that your app lives in. Beautiful, again!
Figure 1.0 - Main.js
.

Figure 1.1 - Server Configurations #1


Figure 1.2 - Server Configurations #2
Figure 1.3 - Server Configurations #3
Adding Router Links
●​ Use Router Links to link to different views/components within our application.
Router links are better than using anchor tags because the click event on them is
intercepted, and no additional request to the server is made.
●​ <router-link> is the component for enabling user navigation in a router-enabled
app. The target location is specified with the to prop. It renders as an <a> tag
with correct href by default, but can be configured with the tag prop. In addition,
the link automatically gets an active CSS class when the target route is active.
●​ <router-link> is preferred over hard-coded <a href="..."> for the following
reasons:
○​ It works the same way in both HTML5 history mode and hash mode, so if
you ever decide to switch mode, or when the router falls back to hash
mode in IE9, nothing needs to be changed.
○​ In HTML5 history mode, router-link will intercept the click event so that the
browser doesn't try to reload the page.
○​ When you are using the base option in HTML5 history mode, you don't
need to include it in prop's URLs.
Figure 1.0 - routes.js
Figure 1.1 - App.vue
Figure 1.2 - Output
Route Parameters
●​ Route Params - the unique ID following the main directory in the URL
●​ We can tell Vue js its route parameter by giving it its syntax
●​ A dynamic segment is denoted by a colon :. When a route is matched, the value
of the dynamic segments will be exposed as this.$route.params in every
component. Therefore, we can render the current user ID by updating User's
template

Figure 1.0 - Route Params #1

Figure 1.1 - Route Params #2


Figure 1.2 - routes.js
Figure 1.3 - singleBlog.vue
Posting to Firebase (Hooking up to Firebase #1)
●​ Hook up your Vue application to Firebase and post your new blog data to a
NoSQL database.
●​ Firebase essentially lets us store data in a NoSQL database which means we're
storing it as JavaScript objects in collections rather than in tables or cells.
●​ https://firebase.google.com
●​ Edit your rules in order to actually write data
●​ In the rules tab on Firebase, change the write property into true in order to add
data to the database.
●​ However if you go on production then you don't want to go with these rules
because that basically means anyone can add data to this so you want to set up
some kind of authentication rules instead.

Figure 1.0 - Console.firebase.google.com


Figure 1.1 - Root URL for Database

Figure 1.2 - Rules Database


Figure 1.3 - Change the Write Property into True
Figure 1.4 - addBlog.vue
Figure 1.5 - Posts fetched by Database
Figure 1.6 - Output, on Console, select Response
Figure 1.7 - Output, Key Value Pairs or Properties being Passed to Firebase Database

.
Retrieving Posts from Firebase (Hooking up to Firebase #1)

Figure 1.0 - Unique Key of Each Object


Figure 1.1 - singleBlog.vue
Figure 1.2 - showBlogs.vue
Figure 1.3 - Output (Retrieve Posts from Firebase

You might also like