Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Last active May 11, 2018 04:08
Show Gist options
  • Save jendiamond/ac7ef0fb43e3505b5515f8dc19b8aa88 to your computer and use it in GitHub Desktop.
Save jendiamond/ac7ef0fb43e3505b5515f8dc19b8aa88 to your computer and use it in GitHub Desktop.

DIRECTIVES | METHODS | EXAMPLES | EVENTS | TWO WAY BINDING | COMPUTED PROPERTIES | npm | Zurb foundation | Shapes & Colors | Publishing | Vue Press | Vue Press Tutorial | CH 8

https://vuejs.org/v2/examples/

https://vuejs.org/v2/examples/commits.htmlhttps://vuejs.org/v2/examples/svg.html https://vuejs.org/v2/examples/todomvc.html https://vuejs.org/v2/examples/hackernews.html)

Module Resources & Useful Links

Vue API


DIRECTIVES

https://012.vuejs.org/guide/directives.html
https://012.vuejs.org/api/directives.html A directive is a special token in the markup, the prefix v-, that tells the library to do something to a DOM element.
<element prefix-directiveId="[argument:] expression [| filters...]"> </element>

<div v-text="message"></div>

The prefix is v which is the default.
The directive ID is text
he expression is message.
This directive instructs Vue.js to update the div’s textContent whenever the message property on the Vue instance changes.

Inline Expressions

<div v-text="'hello ' + user.firstName + ' ' + user.lastName"></div>

Argument

Filters

Multiple Clauses

These directives can bind themselves to a property on the Vue instance, or to an expression which is evaluated in the context of the instance. When the value of the underlying property or expression changes, the update() function of these directives will be called asynchronously on next tick.

  • v-text
  • v-html
  • show
  • class
  • v-attr
  • v-style
  • v-on
  • v-model
  • v-repeat

Literal directives treat their attribute value as a plain string; they do not attempt to bind themselves to anything. All they do is executing the bind() function once. Literal directives can also accept mustache expressions inside their value - please refer to Dynamic Literal for more details.

  • v-transition
  • v-ref Mustache expressions in other literal directives, e.g. are evaluated only once. After the directive has been compiled, it will no longer react to value changes.
  • v-el Mustache expressions in other literal directives, e.g. are evaluated only once. After the directive has been compiled, it will no longer react to value changes.

Empty directives do not require and will ignore their attribute value.

  • v-pre

  • v-cloak

  • v-once This directive ensures that an element is only rendered once, and when Vue.js re-renders the page, the element and all of its children will be considered as static content and thereby skipped.
    <h1 v-once>{{ title }}</h1>

  • v-if

  • v-show

  • v-else

  • v-for

  • v-bind

  • v-model

  • v-on

  • v-transition You can use the mustache syntax to make a literal directive reactive:is the only directive that has this feature.
    <div v-show="showMsg" v-transition="{{dynamicTransitionId}}"></div>


METHODS

https://www.youtube.com/watch?v=2MAoq2-2nnE



EVENTS

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document.

Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).

When an event occur in HTML, the event belongs to a certain event object, like a mouse click event belongs to the MouseEvent object.

The default event object we can listen to on the click event
it holds the coordinates of where the click event happened

List: https://www.w3schools.com/jsref/dom_obj_event.asp

AnimationEvent - For CSS animations
ClipboardEvent - For modification of the clipboard
DragEvent - For drag and drop interaction
FocusEvent - For focus-related events
HashChangeEvent - For changes in the anchor part of the URL
InputEvent - For user input
KeyboardEvent - For keyboard interaction
MouseEvent - For mouse interaction
PageTransitionEvent - For navigating to, and away from, web pages
PopStateEvent - For changes in the history entry
ProgressEvent - For the progress of loading external resources
StorageEvent - For changes in the window's storage area.
TouchEvent - For touch interaction
TransitionEvent - For CSS transitions
UiEvent - For user interface interaction
WheelEvent - For mousewheel interaction


v-on modifiers are directive postfixes denoted by a dot.

Event Modifiers help keep the methods purely about data logic rather than having to deal with DOM event details or often needing to call event.preventDefault() or event.stopPropagation()

+ .stop
+ .prevent
+ .capture
+ .self
+ .once
<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="doThis"></a>

<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- just the modifier -->
<form v-on:submit.prevent></form>

<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>

<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>

Order matters when using modifiers
because the relevant code is generated in the same order.
Therefore using v-on:click.prevent.self will prevent all clicks
while v-on:click.self.prevent will only prevent clicks on the element itself.


Vue has key modifiers for v-on
When listening for key events, we can check for common key codes.

<!-- only call `vm.submit()` when the `keyCode` is 13 -->
<input v-on:keyup.13="submit">

Remembering all the keyCodes is a hassle, so Vue provides aliases for the most commonly used keys:

<!-- same as above -->
<input v-on:keyup.enter="submit">

<!-- also works for shorthand -->
<input @keyup.enter="submit">

Here’s the full list of key modifier aliases:

.enter
.tab
.delete (captures both “Delete” and “Backspace” keys)
.esc
.space
.up
.down
.left
.right

You can also define custom key modifier aliases via the global config.keyCodes object:

// enable `v-on:keyup.f1`
Vue.config.keyCodes.f1 = 112

TWO WAY BINDING

v-model sets up 2-way binding
v-on && v-bind === v-model

COMPUTED PROPERTIES

Computed properties can be used to do quick calculations of properties that are displayed in the view. These calculations will be cached and will only update when needed.

There are multiple ways in Vue to set values for the view. This includes directly binding data value to the view, using simple expressions or using filters to do simple transformations on the content. In addition to this, we can use computed properties to calculate display value based on a value or a set of values in the data model.

dependent properties
use it like a property
everything stored in computed can be used just like you use a property in the data object
is always a String
only updates when it observes changes in the data

new Vue({
  el: '#app',
  data: {
    counter: 0;
  },
  computed: {
    output: function(){
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5';
    }
  },
  methods: {
  }
});

WATCH OBJECT

new Vue({
  el: '#app',
  data: {
    counter: 0;
  },
  computed: {
    output: function(){
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5';
    }
  },
  watch: {
  
  },
  methods: {
  }
});

SHORTCUTS

v-on:click === @click

v-bind:href === :href

PROPERTIES

https://developer.mozilla.org/en-US/docs/Web/Events/keydown

Dash is not a valid character in a property name.

So you can either write 'background-color' on a string or backgroundColor

keydown - The keydown event is fired when a key is pressed down. Unlike the keypress event, the keydown event is fired for keys that produce a character value and for keys that do not produce a character value.

keyup keypress input

clientX

https://developer.mozilla.org/en-US/docs/Web/Events/click

    updateCoordinates: function(event) {
      this.x = event.clientX;
      this.y = event.clientY;
    },
     updateCoordinates: function(whatever) {
      this.x = whatever.screenX;
      this.y = whatever.screenY;
    },
Assumes event obj when NO ()

when () assumes we're going to pass argument and doesm't pass the event

$event Vue

https://vuejs.org/v2/guide/events.html

Communicating between Components

As a Child Element you deckarewhich things are we going to allow in

Props should only be nested 1 or 2 deep

State pieces of information that are changing in an app
https://www.robolink.com/programming-basics-state/
https://www.youtube.com/watch?v=jRtdbSKWFqk
https://www.youtube.com/watch?v=MGEx35FjBuo

4 Programming Paradigms In 40 Minutes

don't update a prop like it's data


Emitting the changes to the parent

$emit - built into VueJS this.emit click event && click handler (what we should do once we do the event)

custom event

In Java
Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double

In JS primitive
Primitives are values, they have no properties.
In JavaScript there are 5 primitive types: undefined , null , boolean , string and number.
Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts.
referenceType

https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value

A variable can hold one of two value types: primitive values or reference values.

Primitive values are data that are stored on the stack.
Primitive value is stored directly in the location that the variable accesses.
Reference values are objects that are stored in the heap.
Reference value stored in the variable location is a pointer to a location in memory where the object is stored.
Primitive types include Undefined, Null, Boolean, Number, or String.

The Basics:

Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties.

Updated:

JavaScript has 6 primitive data types: string, number, boolean, null, undefined, symbol (new in ES6). With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Validation

firstName: String

You can pass a function as a prop (not used very often)

The Event Bus

Homework was Section 5 - Understanding the VueJS Instance

  • SPA - Single Page App
  • PWA - Progressive Web App

proxy - a figure that can be used to represent the value of something in a calculation.

https://codingexplained.com/coding/front-end/vue-js/proxying

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

handler
Placeholder object which contains traps. traps
The methods that provide property access. This is analogous to the concept of traps in operating systems. target
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.

$data -
https://vuejs.org/v2/api/

Virtual DOM vs Shadow DOM

Vue.js and React both use Virtual DOM so it is a known concept by many but often it is confused with Shadow Dom. ...

Shadow DOM refers to the ability of the browser to include a subtree of DOM elements into the rendering of a document,
but not into the main document DOM tree.

https://vuejsfeed.com/blog/learn-the-differences-between-shadow-dom-and-virtual-dom

getters / setteres

https://en.wikipedia.org/wiki/Mutator_method

anti-pattern - https://www.youtube.com/watch?v=WSgP85kr6eU https://coderanch.com/t/640403/Getters-Setters-anti-pattern-don

https://vuejs.org/v2/guide/computed.html
Computed properties are by default getter-only, but you can also provide a setter when you need it:

https://vuejs.org/v2/guide/reactivity.html

https://stackoverflow.com/questions/40871513/using-computed-property-setter-and-getter-to-update-data-properties

https://codeburst.io/vuex-getters-are-great-but-dont-overuse-them-9c946689b414

Don't use Ref!

mount

infrequent

template

DON'T USE

new Vue {
 el: #app3,
 template: `<h1>`
}

Component Syntax

Vue.component(, template:<h1>Jen</h1>)

Vue.component

Life Cycle Hooks

a function that runs within a specific time frame
Each Vue 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.


install globally
github.com/vue/vue-cli

sudo npm install -g @vue/cli

!!

@ - part of the npm ecosystem

command line interface

A command line interface (CLI) is a type of human-computer interface (i.e., a way for humans to interact with computers) that relies solely on textual input and output. That is, the entire display screen, or the currently active portion of it, shows only characters (and no images), and input is usually performed entirely with a keyboard.

The CLI gets its name from the fact that it is an interface which contains command lines. A command line is a space on the display screen in which commands (i.e., instructions telling a computer to do something) are typed in by the user. Pressing the ENTER key after typing in a command causes that command to be passed to the shell. A shell, also referred to as a command interpreter, is a program that provides the CLI as well as reads commands that are typed on a keyboard and then executes (i.e., runs) them. The results of executing many, but not all, commands are also shown on the command line.

CLIs stand in sharp contrast to graphical user interfaces (GUIs), the other main type of human-computer interface. GUIs feature the use of graphic images, including windows, icons and menus. These objects are manipulated by a mouse (and can usually be manipulated to a limited extent by a keyboard as well).

vue create jenjen

https://docs.npmjs.com/getting-started/what-is-npm

  • install node not as sudo
    don't use apt-get install for node
    uninstall node using apt-get

  • install npm not as sudo

  • install n / nvm

https://gist.github.com/isaacs/579814
https://www.google.com/search?client=ubuntu&channel=fs&q=linux+install+node+not+as+sudo&ie=utf-8&oe=utf-8


  • $ npm init gives you...
{
  name: ,
  version: ,
  description: ,
  main: ,
  scripts: ,
  author: ,
  license: ,
}

  • $ npm init
  • $ git init
  • $ npm install vue
  • $ npm

To update npm

  • $ sudo npm install-g npm

Install nvm / n

  • $ ``

https://github.com/tj/n


Webpack-simple

https://docs.npmjs.com/getting-started/what-is-npm

  • $ -D - devDepenency

  • App.vue file is the component

https://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489

What We’ll Cover in This Quick Tutorial:

Create a vue project Create a Heroku app Configure vue project so that Heroku can serve up our vue code. Push and deploy! Even though I’ve been mostly on backend bot frameworks in Golang for drinkeasy.co (a chatbot that sells alcohol), Vue.js is still my top choice for things like one-off marketing or hobby sites.

Here we go…

  1. Generate a Vue.js Project First off, install Vue.js (instructions here). We’ll also need Vue’s CLI to easily generate our project. (As a bonus option, feel free to use the awesome Yarn dependency manager rather than npm for these examples. Just substitute the npm command with yarn instead throughout the rest of this tutorial):

npm install --global vue-cli vue init webpack cd npm install npm run dev Make sure your browser window opens and displays the starter project.

  1. Create Your Heroku App Heroku is a platform that let’s us easily deploy and host our Vue.js app. If you haven’t already, sign up for a Heroku account here. Then, install Heroku’s CLI tool via the instructions here. Then, let’s create our Heroku app:

heroku create When this is done, you’ll get a fresh URL to your project, i.e. https://.herokuapp.com. Make sure you head over to the URL and see a temporary Heroku landing page there.

Lastly, in order to avoid having Heroku install needless development dependencies when deploying later, let’s go ahead and set the NODE_ENV setting to production :

heroku config:set NODE_ENV=production --app 3. Create a server.js and Build Your Site Since Vue is only a frontend library, the easiest way to host it and do things like serve up assets is to create a simple Express friendly script that Heroku can use to start a mini-web server. Read up quickly on Express if you haven’t already. After that, add express:

npm install express --save Now add a server.js file to your project’s root directory:

// server.js var express = require('express'); var path = require('path'); var serveStatic = require('serve-static'); app = express(); app.use(serveStatic(__dirname + "/dist")); var port = process.env.PORT || 5000; app.listen(port); console.log('server started '+ port); IMPORTANT: What you probably noticed is that this will serve up a dist directory. dist is a predefined directory that Vue.js builds which is a compressed, minified version of your site. We’ll build this and then tell Heroku to run server.js so Heroku hosts up this dist directory:

npm run build You should see an output dist directory now.

Let’s test our server.js file by running it:

node server.js Now go to http://localhost:5000 and make sure your app loads. This is the actual site Heroku will serve up.

Lastly, we’ll have to edit our start script in package.json to start our node server, as Heroku will automatically look for this script when looking for how to run a node.js app.

// package.json { "name": "", "version": "1.0.0", "description": "A Vue.js project", "author": "", "private": true, "scripts": { "dev": "node build/dev-server.js", "build": "node build/build.js", "start": "node server.js", <--- EDIT THIS LINE HERE ... 4. Git Init and Add Your Heroku Remote Repository Heroku allows us to push to a remote repository so we’ll first need to create our own git repository:

git init Now let’s add our Heroku remote repository:

heroku git:remote --app Let’s keep our generated dist directory so that we can always keep a pristine copy of what we’ve deployed to Heroku by removing dist/ from .gitigore

.DS_Store node_modules/ dist/ <--- REMOVE THIS LINE npm-debug.log* yarn-debug.log* yarn-error.log* test/unit/coverage test/e2e/reports selenium-debug.log

Editor directories and files

.idea *.suo .ntvs *.njsproj *.sln Now, most importantly, let’s add and commit our code files:

git add . && git commit -a -m "Adding files." 5. Push Your Code to Deploy! Now all we need to deploy to Heroku is:

git push heroku master This will take our committed code, push it to Heroku’s remote repository, run our start command in package.json which will serve up our freshly built dist directory.

If you come across any issues, you can always run heroku logs to troubleshoot.

If deployment is successful, test out your project’s URL https://.herokuapp.com and you’re done!

@jendiamond
Copy link
Author

@jendiamond
Copy link
Author

jendiamond commented Mar 23, 2018

Virtual DOM

https://www.google.com/search?q=Virtual+DOM&oq=Virtual+DOM&aqs=chrome..69i57j0l5.1285j0j1&sourceid=chrome&ie=UTF-8

https://www.codecademy.com/articles/react-virtual-dom

http://reactkungfu.com/2015/10/the-difference-between-virtual-dom-and-dom/

DOM stands for Document Object Model and is an abstraction of a structured text. For web developers, this text is an HTML code, and the DOM is simply called HTML DOM. Elements of HTML become nodes in the DOM.

So, while HTML is a text, the DOM is an in-memory representation of this text.

So, whenever we want to dynamicly change the content of the web page, we modify the DOM:

var item = document.getElementById("myLI");
item.parentNode.removeChild(item);
document is an abstraction of the root node, while getElementById, parentNode and removeChild are methods from HTML DOM API.

@jendiamond
Copy link
Author

jendiamond commented Mar 23, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment