Skip to content

Instantly share code, notes, and snippets.

@danielschmitz
Last active August 29, 2018 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielschmitz/c6f471491c320577be5c2c55a438170e to your computer and use it in GitHub Desktop.
Save danielschmitz/c6f471491c320577be5c2c55a438170e to your computer and use it in GitHub Desktop.
ES6 Dicas

Variáveis

  • usar let na maioria das vezes (escopo)
  • usar const sempre que a variável não alterar de calor
  • objetos são na maioria das vezes const, mesmo que suas propriedades sejam alteradas

Template Literais

Inserir variaáveis dentro do texto

Antigo:

let surname = "Schmitz"
let name = " Daniel " + surname

Novo:

let surname = "Schmitz"
let name = ` Daniel ${surname} `

Destructing

Se uma funcao retorna um objeto com varios parametros, pode-se usar destructing para obter somente alguns deles

function bar() { return {a:1, b:2, c:3 } }
let {a, c} = bar()  // a = 1, b = undefinded
let {b} = bar() // b = 2

Valores padrão em parâmetros

Antes

var multiply = function(x, y) {
   y = y | 1;
   return x * y;
};

multiply(3, 2); // 6
multiply(3); // 3

Novo:

const multiply = (x, y = 1) => {
  return x * y
}

multiply(3, 2) // 6
multiply(3) // 3

ou até melhor: const multiply = (x, y = 1) => x * y

Arrow Functions

Duas funcionalidades basicas: mantém o escopo e nao precisa do function.

Antes:

var sum = function(x, y) {
  return x + y;
};

Novo:

const sum = (x, y) => {
  return x + y
}

ou: const sum = (x, y) => x + y

let bar = (a, b) => a * b

// comum no uso do map, forEach, sort
let arr = [ 5, 6, 7, 8, 'a' ];
let b = arr.map( item => item + 3 );
console.log(b); // [ 8, 9, 10, 11, 'a3' ]

// Exemplo foreach
arr.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Uso comum no Vue:

// getAll retorna um promise do axios
getAll().then(r => {
          this.table = r.data
        })

Uso comum em um objeto do Quasar

captura de tela de 2018-02-04 11-50-45

Uso duplo em um objeto do Quasar, o this continua o escopo do Vue

image

Módulos

Exemplo de criação de um modulo:

http.js

import axios from 'axios'

const client = axios.create({
  baseURL: 'http://127.0.0.1:8181',
  timeout: 1000,
  headers: {'Content-Type': 'application/json'}
})

export default client

usando este módulo:

category.js

import http from '../http'

export const getAll = () => {
  return http.get('/category')
}

export const deleteRow = (row) => {
  return http.delete(`/category`, {data: {id: row.Id}})
}

O category.js tem dois métodos arrow functions que sao exportados para uso. por exemplo:

import { getAll, deleteRow } from '../model/category'

...

handler: () => {
                deleteRow(row).then(r => {
                  Toast.create('Done!')
                  this.refresh()
                })
              }

Outra forma de criar um módulo:

import http from './http'

const CategoryService = {
  getAll: () => {
    return http.get('/categories')
  },
  getById: (id) => {
    return http.get(`/category/${id}`)
  }
}

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