Skip to content

Instantly share code, notes, and snippets.

@febritecno
Last active September 14, 2021 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save febritecno/b247b2ee1efcd5dad1325a9d94d4f547 to your computer and use it in GitHub Desktop.
Save febritecno/b247b2ee1efcd5dad1325a9d94d4f547 to your computer and use it in GitHub Desktop.
sample store vuex
/// https://vuex.vuejs.org/guide/actions.html
// if use computed mapState, can use like local props data() -> this.foo
//state
// mapState('filename') -> this.$store.state.items
export const state = () => ({
items: []
})
//getters
// mapGetter('filename') -> this.$store.getter('filename').getItems
// computed: mapState("breadcrumb", ["items"]),
export const getters = {
// getItems: (state) => {
// return state.items
// },
}
//commit
// mapMutation('filename') -> this.$store.commit('breadcrumb/SET',[])
export const mutations = {
SET(state, items) {
state.items = items
},
}
//dispatch
// mapAction('filename') -> this.$store.dispatch('filename'),increment()
export const actions = {
// increment(context) {
// context.commit('increment')
// }
}
export const state = () => ({
srcs: []
})
export const mutations = {
SET_BANNERS(state, banners) {
state.srcs = banners
}
}
export const actions = {
async loadAllBanners({
commit
}) {
const response = await this.$axios.get('/ref/web-slider-top');
const datas = response.data.data;
commit('SET_BANNERS', datas.map(d => d.image))
}
}
export const state = () => ({
title: "",
search: "",
back: -1,
scrollValue: 0
})
//getters
export const getters = {
getBack: (state) => {
return state.back
},
getScrollValue: (state) => {
return state.scrollValue
}
}
//commit
export const mutations = {
SET_TITLE(state, title) {
state.title = title
},
SET_SEARCH(state, keyword) {
state.search = keyword;
},
SET_BACK(state, url) {
state.back = url
},
SET_SCROLLVALUE(state, value) {
state.scrollValue = value
}
}
//dispatch
export const actions = {
async setSearchProd({
commit
}, {
keyword
}) {
commit('SET_SEARCH', keyword)
},
}
export const state = () => ({
carts: [],
totalWeight: 0,
productPrice: 0,
totalPrice: 0,
})
export const mutations = {
SET_CARTS_LOCALFORAGE(state, res) {
state.carts = res.carts;
state.totalPrice = res.totalPrice;
},
SET_CARTS(state, cart) {
state.carts.push(cart);
state.totalPrice = parseInt(state.totalPrice) + (parseInt(cart.price) || parseInt(cart.product.price));
this.$localForage.setItem('carts', {
cart: state.carts,
totalPrice: state.totalPrice
});
},
HARD_UPDATE_TOTAL_PRICE(state, total) {
state.totalPrice = total
},
UPDATE_CART(state, cart) {
let data;
data = state.carts.find(v => v.product.id === cart.id);
if (cart.type === 'plus') {
state.totalWeight = parseInt(data.product.weight) * 1;
state.totalPrice = parseInt(state.totalPrice) + (parseInt(data.price) || parseInt(data.product.price));
data.qty = parseInt(data.qty) + 1;
this.dispatch('cart/SyncQtyToAPI', {data})
} else {
if (data.qty <= 1) {
state.carts = state.carts.filter(v => v.product.id !== cart.id);
this.dispatch('cart/SyncQtyToAPI', {data: data, type: "delete"})
} else {
data.qty = parseInt(data.qty) - 1;
this.dispatch('cart/SyncQtyToAPI', {data})
}
state.totalPrice = parseInt(state.totalPrice) - (parseInt(data.price) || parseInt(data.product.price));
state.totalWeight = parseInt(state.totalWeight) - parseInt(data.product.weight);
}
this.$localForage.setItem('carts', {
cart: state.carts,
totalPrice: state.totalPrice,
totalWeight: state.totalWeight,
});
},
CLEAR_DATA(state) {
state.datas = []
},
RESET_CART(state) {
state.carts= []
state.totalWeight= 0
state.productPrice= 0
state.totalPrice= 0
},
CHECK_CARD(state, prodID) {
const cart = state.carts.find(v => v.product.id === prodID);
cart.checked = !cart.checked
if (cart.checked) {
state.totalPrice = parseInt(state.totalPrice) + ((parseInt(cart.price) || parseInt(cart.product.price)) * parseInt(cart.qty));
} else {
state.totalPrice = parseInt(state.totalPrice) - ((parseInt(cart.price) || parseInt(cart.product.price)) * parseInt(cart.qty));
}
this.$localForage.setItem('carts', {
cart: state.carts,
totalPrice: state.totalPrice
});
},
CHECK_ALL(state, length) {
let totalPrice = 0;
if (length === state.carts.length) {
state.carts.forEach(data => {
data.checked = false
})
} else if (length >= 0) {
state.carts.forEach(data => {
data.checked = true
totalPrice += data.qty * (data.price || data.product.price)
})
}
state.totalPrice = totalPrice;
this.$localForage.setItem('carts', {
cart: state.carts,
totalPrice: state.totalPrice
});
}
}
export const actions = {
async setCarts({
commit
}, {
datas
}) {
this.dispatch('cart/SyncQtyToAPI', {data: datas, type: "add"})
commit('SET_CARTS', datas)
},
async updateQtyCart({
commit
}, {
id,
type
}) {
commit('UPDATE_CART', {
id,
type
})
},
async hardUpdateTotalPrice({
commit
}, {total}) {
commit('HARD_UPDATE_TOTAL_PRICE', total)
},
async checkedAll({
commit
}, {
length
}) {
commit('CHECK_ALL', length)
},
async fetchByServer({
commit
}, {
carts,
totalPrice,
datas
}) {
await datas.map(c => {
c.checked = true;
})
totalPrice = datas
.map((dd) => {
return dd.price * dd.qty
})
.reduce((a, b) => a + b, 0)
await this.$localForage.setItem('carts', {
cart: datas,
totalPrice
}).then(val => {
if (val) {
carts = val.cart;
totalPrice = val.totalPrice
}
commit('SET_CARTS_LOCALFORAGE', {
carts,
totalPrice
})
})
},
async fetchByLocalForage({
commit
}, {
carts,
totalPrice
}) {
await this.$localForage.getItem('carts').then(function (val) {
if (val) {
carts = val.cart;
totalPrice = val.totalPrice
}
commit('SET_CARTS_LOCALFORAGE', {
carts,
totalPrice
})
})
},
async setCartLocalForage({
commit
}) {
let carts = [];
let totalPrice = 0;
this.$localForage.getItem('token').then(async (token) => {
if (token) {
const tokenKey = token.data.token
await this.$axios('/temp-cart', {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenKey}`,
},
}).then(async (datas) => {
let cartdatas = datas.data.data.detail;
this.dispatch('cart/fetchByServer', {
carts,
totalPrice,
datas: cartdatas
})
// await this.$localForage.getItem('carts').then(async (cartLocal) => {
// if (cartLocal) {
// if (cartdatas.length !== cartLocal.cart.length) {
// this.dispatch('cart/fetchByServer', {
// carts,
// totalPrice,
// datas: cartdatas
// })
// } else {
// this.dispatch('cart/fetchByLocalForage', {
// carts,
// totalPrice
// })
// }
// } else {
// this.dispatch('cart/fetchByServer', {
// carts,
// totalPrice,
// datas: cartdatas
// })
// }
// });
})
} else {
this.dispatch('cart/fetchByLocalForage', {
carts,
totalPrice
})
}
})
},
async setCheckedCart({
commit
}, {
prodID
}) {
commit('CHECK_CARD', prodID)
},
async minimumCartsTotal({
getters
}) {
let totalCarts = getters.getTotalPrice;
if (totalCarts < 50000) {
this.$router.push('/cart');
}
},
async SyncQtyToAPI({commit}, {data, type = 'update'}) {
const token = await this.$localForage.getItem('token');
if (token) {
const tokenKey = token.data.token;
let url = '/temp-cart';
const payloads = {
qty: data.qty,
note: data.note,
product: { id: data.product.id },
}
const headers = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenKey}`,
},
}
if (type === 'delete') {
url = '/temp-cart/remove-commerce'
} else {
url = '/temp-cart-commerce'
}
this.$axios.$post(url, payloads, headers)
}
}
}
export const getters = {
getProduct(state) {
return (id) => {
return state.carts.find(v => v.product.id === id);
}
},
getCheckedLength(state) {
return state.carts.filter(v => v.checked === true).length;
},
getTotalPrice(state) {
return state.totalPrice;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment