-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
121 lines (109 loc) · 3.1 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const vm = new Vue ({
el: "#app",
data: {
produtos: {},
produto: false,
carrinho: [],
mensagemAlerta: "Item adicionado",
alertaAtivo: false,
carrinhoAtivo: false,
},
filters: {
numeroPreco(valor) {
return valor.toLocaleString("pt-BR", {style: "currency", currency:"BRL"})
}
},
computed: {
carrinhoTotal() {
let total = 0
if (this.carrinho.length) {
this.carrinho.forEach(item => {
total += item.preco
});
}
return total
}
},
methods: {
fetchProdutos(){
fetch("./api/produtos.json")
.then(res => res.json())
.then(res => this.produtos = res)
},
fetchProduto(id){
fetch(`./api/produtos/${id}/dados.json`)
.then(res => res.json())
.then(res => this.produto = res)
},
abrirModal(id){
this.fetchProduto(id)
window.scrollTo({
top: 0,
behavior: "smooth",
})
},
fecharModal({target, currentTarget}){
if (target === currentTarget) {
this.produto = false
}
},
clickForaCarrinho({target, currentTarget}){
if (target === currentTarget) {
this.carrinhoAtivo = false
}
},
adicionarItem(){
this.produto.estoque--
const {id, nome, preco} = this.produto
this.carrinho.push({id, nome, preco})
this.alerta(`${nome} foi adicionado ao carrinho`)
},
removerItem(index){
this.carrinho.splice(index, 1)
},
checarLocalStorage(){
if (window.localStorage.carrinho) {
this.carrinho = JSON.parse(window.localStorage.carrinho)
}
},
compararEstoque(){
const items = this.carrinho.filter(item => {
if (item.id === this.produto.id ) {
return true
}
})
this.produto.estoque = this.produto.estoque - items.length
},
alerta(mensagem){
this.mensagemAlerta = mensagem
this.alertaAtivo = true
setTimeout(() => {
this.alertaAtivo = false
}, 1500)
},
router(){
const hash = document.location.hash
if (hash) {
this.fetchProduto(hash.replace("#", ""))
}
},
},
watch: {
produto(){
document.title = this.produto.nome || "Techno"
const hash = this.produto.id || ""
history.pushState(null, null, `#${hash}`)
if (this.produto) {
this.compararEstoque()
}
},
carrinho(){
window.localStorage.carrinho = JSON.stringify(this.carrinho)
}
},
created() {
this.router()
this.fetchProdutos()
this.checarLocalStorage()
},
})