Delete session.storage on changing restaurant page - session

I'm using Vuejs 2 and vue router to create this website.
It has a cart saved in session.storage.
I would like to delete the cart (session.storage) when the restaurant page change.
I've tried to save the slug of the restaurant and compare it to the current slug:
setSlug() {
sessionStorage.setItem("slug", this.$route.params.slug);
},
checkSlug() {
if (sessionStorage.getItem("slug") != this.$route.params.slug) {
sessionStorage.clear();
}
},
But it doesn't work.
How can I achieve this?
Thank you.
TheRestaurant.vue
export default {
name: "TheRestaurant",
data() {
return {
restaurant: {},
cart: {},
quantity: 1,
partialTotal: 0,
total: 0,
};
},
methods: {
//get the restaurant and the dishes with axios call and set the data
getRestaurant() {
axios
.get("/api/restaurants/" + this.$route.params.slug)
.then((response) => {
this.restaurant = response.data;
})
.catch((error) => {
console.log(error);
});
},
showDetails(id) {
let modal = document.getElementById("modal-" + id);
modal.classList.replace("d-none", "d-flex");
},
hideDetails(id) {
let modal = document.getElementById("modal-" + id);
modal.classList.replace("d-flex", "d-none");
},
addToCart(dish) {
if (sessionStorage.getItem("cart") == null) {
sessionStorage.setItem("cart", JSON.stringify([]));
}
let cart = JSON.parse(sessionStorage.getItem("cart"));
let index = cart.findIndex((item) => item.id == dish.id);
if (index == -1) {
dish.quantity = 1;
cart.push(dish);
} else {
cart[index].quantity++;
}
sessionStorage.setItem("cart", JSON.stringify(cart));
this.cart = JSON.parse(sessionStorage.getItem("cart"));
this.partialTotal = round(
this.cart.reduce(
(acc, dish) => acc + dish.price * dish.quantity,
0
),
2
);
sessionStorage.setItem(
"partialTotal",
JSON.stringify(this.partialTotal)
);
this.total = this.partialTotal + this.restaurant.delivery_price;
sessionStorage.setItem("total", JSON.stringify(this.total));
},
removeOneFromCart(dish) {
let cart = JSON.parse(sessionStorage.getItem("cart"));
let index = cart.findIndex((item) => item.id == dish.id);
if (index !== -1) {
cart[index].quantity--;
if (cart[index].quantity == 0) {
cart.splice(index, 1);
}
}
sessionStorage.setItem("cart", JSON.stringify(cart));
this.cart = JSON.parse(sessionStorage.getItem("cart"));
this.partialTotal = round(
this.cart.reduce(
(acc, dish) => acc + dish.price * dish.quantity,
0
),
2
);
sessionStorage.setItem(
"partialTotal",
JSON.stringify(this.partialTotal)
);
this.total = this.partialTotal + this.restaurant.delivery_price;
sessionStorage.setItem("total", JSON.stringify(this.total));
},
removeAllFromCart(dish) {
let cart = JSON.parse(sessionStorage.getItem("cart"));
let index = cart.findIndex((item) => item.id == dish.id);
if (index !== -1) {
cart.splice(index, 1);
}
sessionStorage.setItem("cart", JSON.stringify(cart));
this.cart = JSON.parse(sessionStorage.getItem("cart"));
this.partialTotal = round(
this.cart.reduce(
(acc, dish) => acc + dish.price * dish.quantity,
0
),
2
);
sessionStorage.setItem(
"partialTotal",
JSON.stringify(this.partialTotal)
);
this.total = this.partialTotal + this.restaurant.delivery_price;
sessionStorage.setItem("total", JSON.stringify(this.total));
},
},
mounted() {
this.getRestaurant();
this.cart = JSON.parse(sessionStorage.getItem("cart"));
this.partialTotal = JSON.parse(sessionStorage.getItem("partialTotal"));
this.total = JSON.parse(sessionStorage.getItem("total"));
},
};
router.js
import Vue from "vue";
import VueRouter from "vue-router";
import Restaurant from "./pages/TheRestaurant.vue";
import Home from "./pages/TheMain.vue";
import Cart from "./pages/TheCart.vue";
import Search from "./pages/AdvancedSearch.vue";
//put all the different pages below
Vue.use(VueRouter);
/**
* #type {import("vue-router").RouteConfig[]}
*/
const routes = [
{
path: "/",
component: Home,
name: "home.index",
meta: {
title: "Deliveboo Homepage",
},
},
{
path: "/cart",
component: Cart,
name: "cart.index",
meta: {
title: "Deliveboo Cart",
},
},
{
path: "/search",
component: Search,
name: "search.index",
meta: {
title: "Deliveboo Search Restaurants",
},
},
{
path: "/:slug",
component: Restaurant,
name: "restaurant.index",
meta: {
title: "Deliveboo Restaurant",
},
},
];
const router = new VueRouter({
//it must contain an array of routes
routes,
mode: "history",
});
export default router;

If I understood your hierarchy and logic of components correctly,
in the mounted hook of Home and Search components you can reset your session.storage.

Related

redux toolkit How to change the price when the variability of the product changes

There is a json file
{
"items": [
{ "id": "0", "imageUrl": "https://dodopizza.azureedge.net/static/Img/Products/f035c7f46c0844069722f2bb3ee9f113_584x584.jpeg", "title": "Пепперони Фреш с перцем", "types": [0, 1], "sizes": [26, 30, 40], "price": 803, "category": 0, "rating": 4 },
]
}
Pizza is loaded from the file, and all data is output to react
http://joxi.ru/krDaNEVSGRlpJm
Tell me please, how in redux toolkit to make the price of the product increase depending on the selected parameter sizes. That is, if the value 26 is selected, then you need to increase the amount by 100 rubles, if the size is 30, then by 200 rubles.
I tried to do it with various crutches, but I don't have enough knowledge
Here is the code where I get the pizzas
import { createSlice } from "#reduxjs/toolkit";
const initialState = {
pizzas: [],
itemsCount: 0,
isLoading: true,
};
export const getItemsSlice = createSlice({
name: "items",
initialState,
reducers: {
setItems(state, action) {
state.pizzas = action.payload;
},
setItemsCount(state, action) {
state.itemsCount = action.payload;
},
setIsLoading(state, action) {
state.isLoading = action.payload;
},
},
});
export const { setItems, setItemsCount, setIsLoading } = getItemsSlice.actions;
export default getItemsSlice.reducer;
React output code
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { addPizzaInCart } from "../../../redux/slices/CartSlice";
import { typeName } from "../../../redux/slices/GetItemsSlice";
import styles from "./PizzaBlock.module.scss";
function PizzaBlock({ id, imageUrl, title, price, types, sizes }) {
const [activeType, setActiveType] = React.useState(0);
const [activeSize, setActiveSize] = React.useState(0);
const dispatch = useDispatch();
const itemInCart = useSelector((state) => state.cart.pizzasInCart.find((obj) => obj.id === id && obj.type === typeName[activeType] && obj.size === sizes[activeSize]));
const addedCount = itemInCart ? itemInCart.count : 0;
const pizza = {
id,
imageUrl,
title,
price,
type: typeName[activeType],
size: sizes[activeSize],
};
const onClickAddPizza = () => {
dispatch(addPizzaInCart(pizza));
};
const onChangeSize = (i) => {
setActiveSize(i);
};
return (
<div className={styles.item}>
<img className={styles.item__image} src={imageUrl} alt="Pizza" />
<Link to={`/product/${pizza.id}`} className={styles.item__title}>
{title}
</Link>
<div className={styles.item__selector}>
<ul>
{types.map((type, i) => (
<li className={activeType === i ? styles.active : ""} onClick={() => setActiveType(type)} key={i}>
{typeName[type]}
</li>
))}
</ul>
<ul>
{sizes.map((size, i) => (
<li className={activeSize === i ? styles.active : ""} onClick={() => onChangeSize(i)} key={i}>
{size} см.
</li>
))}
</ul>
</div>
<div className={styles.item__bottom}>
<div className={styles.item__price}>от {Math.trunc(pizza.price * (pizza.size / 100 + 1))} ₽</div>
<div className={styles.item__buttons}>
<button className={`${styles.button} ${styles.button_outline} ${styles.button_add}`} onClick={onClickAddPizza}>
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.8 4.8H7.2V1.2C7.2 0.5373 6.6627 0 6 0C5.3373 0 4.8 0.5373 4.8 1.2V4.8H1.2C0.5373 4.8 0 5.3373 0 6C0 6.6627 0.5373 7.2 1.2 7.2H4.8V10.8C4.8 11.4627 5.3373 12 6 12C6.6627 12 7.2 11.4627 7.2 10.8V7.2H10.8C11.4627 7.2 12 6.6627 12 6C12 5.3373 11.4627 4.8 10.8 4.8Z" fill="white" />
</svg>
<span>Добавить</span>
{addedCount > 0 && <i>{addedCount}</i>}
</button>
</div>
</div>
</div>
);
}
export default PizzaBlock;
There are items with sizes 26, 30 and 40. When I change the active size, that is, I press the button 26, 30 or 40, I need the price for pizza to automatically increase by 0, 100 and 200 rubles, depending on the size of the pizza. I tried using state to pass size parameters and already substitute the required amount in redux, but in this case problems appeared, the value of this state was applied to all pizzas at once, but only to the current one
Here Cart logic
import { createSlice } from "#reduxjs/toolkit";
const initialState = {
totalPricePizzasInCart: 0,
totalCountPizzasInCart: 0,
pizzasInCart: [],
};
export const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addPizzaInCart(state, action) {
const findItem = state.pizzasInCart.find((obj) => {
return obj.id === action.payload.id && obj.type === action.payload.type && obj.size === action.payload.size;
});
if (findItem) {
findItem.count++;
} else {
state.pizzasInCart.push({
...action.payload,
count: 1,
});
}
state.totalPricePizzasInCart = state.pizzasInCart.reduce((sum, obj) => {
return Math.trunc(obj.price * (obj.size / 100 + 1)) * obj.count + sum;
}, 0);
state.totalCountPizzasInCart = state.pizzasInCart.reduce((count, obj) => {
return obj.count + count;
}, 0);
},
minusPizzaInCart(state, action) {
const findItem = state.pizzasInCart.find((obj) => {
return obj.id === action.payload.id && obj.type === action.payload.type && obj.size === action.payload.size;
});
if (findItem && findItem.count > 0) {
findItem.count--;
state.totalPricePizzasInCart = state.totalPricePizzasInCart - Math.trunc(findItem.price * (findItem.size / 100 + 1));
}
state.totalCountPizzasInCart = state.pizzasInCart.reduce((count, obj) => {
return obj.count + count;
}, 0);
},
removePizzaInCart(state, action) {
state.pizzasInCart = state.pizzasInCart.filter((obj) => {
return obj.id !== action.payload.id || obj.type !== action.payload.type || obj.size !== action.payload.size;
});
state.totalPricePizzasInCart = state.pizzasInCart.reduce((sum, obj) => {
return Math.trunc(obj.price * (obj.size / 100 + 1)) * obj.count + sum;
}, 0);
state.totalCountPizzasInCart = state.pizzasInCart.reduce((count, obj) => {
return obj.count + count;
}, 0);
},
clearPizzasInCart(state) {
state.pizzasInCart = [];
state.totalPricePizzasInCart = 0;
state.totalCountPizzasInCart = 0;
},
},
});
export const { addPizzaInCart, removePizzaInCart, minusPizzaInCart, clearPizzasInCart } = cartSlice.actions;
export default cartSlice.reducer;
github github.com/antonboec1994/reactPizza.git
Store :
import { configureStore, createSlice } from "#reduxjs/toolkit";
const initialState = {
basePrice: 100,
total: 0,
itemsCount: 0
};
export const getItemsSlice = createSlice({
name: "items",
initialState,
reducers: {
addToCart(state, action) {
console.log(action.payload);
state.itemsCount = action.payload;
state.total = state.itemsCount * state.basePrice;
}
}
});
export const { addToCart } = getItemsSlice.actions;
export const store = configureStore({
reducer: {
pizza: getItemsSlice.reducer
}
});
export default getItemsSlice.reducer;
Component :
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../store/__counterStore__";
const PizzaComponent = () => {
const dispatch = useDispatch();
const storeData = useSelector((state) => state.pizza);
console.log(storeData);
const [itemCount, setItemCount] = React.useState(0);
const handleAdd = () => {
setItemCount(itemCount + 1);
dispatch(addToCart(itemCount));
};
return (
<div>
<button onClick={handleAdd}>Add 1 Pitzzza</button>
<h2>Cart Price</h2>
<div>{storeData.total}</div>
</div>
);
};
export default PizzaComponent;
I just updated price for one type of pitza, what you can do is you can updated price according to type of different pitzas, by setting dispatch different kind of payload of you can put locgic in your reducer.
I tried to make it simple, since purpose is to understand the folw and logic.
EDIT:
CODESANDBOX

How to use React useContext with leaflet routing machine and react leaflet?

I'm trying to use a useContext hook inside a react-leaflet controlComponent but I have an error when my context fires the update function.
I use a react-leaflet controlComponent because of leaflet routing machine. I think the code + the error are better than word:
MainBoard.tsx
export const CartographyContext: React.Context<CartographyContextType> = React.createContext<CartographyContextType>({ positions: [] });
...
const routeSummaryValueContext = React.useMemo(
() => ({ routeSummary, setRouteSummary }),
[routeSummary]
);
const elevationProfileValueContext = React.useMemo(
() => ({ elevationProfile, setElevationProfile }),
[elevationProfile]
);
........
<CartographyContext.Provider value={{ positions, elevationProfileValueContext, routeSummaryValueContext, positionsValueContext, addPosition, changePosition }}>
.........
<RoutingMachine
orsOptions={{
....
}} />
..........
</CartographyContext.Provider>
RoutingMachine.tsx:
const CreateRoutineMachineLayer = (props: any) => {
const geoService = new GeoLocalisationService();
const cartographyContext: CartographyContextType = React.useContext<CartographyContextType>(CartographyContext);
const [routes, setRoutes] = React.useState<any[]>();
React.useEffect(() => {
if (routes) {
//The line which cause the error
cartographyContext.elevationProfileValueContext.setElevationProfile(geoService.getElevationProfile(decodePolyline(routes[0].geometry, true)));
const summary: RouteSummary = {
ascent: routes[0].routeSummary.ascent,
descent: routes[0].routeSummary.descent,
distance: routes[0].routeSummary.distance,
estimatedDuration: routes[0].routeSummary.duration
}
cartographyContext.routeSummaryValueContext.setRouteSummary(summary);
}
}, [routes]);
const { orsOptions } = props;
const instance = L.Routing.control({
router: new OpenRouteRouter(orsOptions),
lineOptions: {
styles: [{ color: "#3933ff", weight: 4 }],
extendToWaypoints: true,
missingRouteTolerance: 0
},
routeWhileDragging: true,
autoRoute: true,
geocoder: new geocoder.Geocoder(),
}).on('routesfound', (e) => {
setRoutes(e.routes);
});
useMapEvents({
click: (e: L.LeafletMouseEvent) => {
if (instance.getWaypoints().length === 2 && instance.getWaypoints()[0].latLng == null) {
instance.spliceWaypoints(0, 1, new L.Routing.Waypoint(e.latlng, null, {}));
} else if (instance.getWaypoints().length === 2 && instance.getWaypoints()[1].latLng == null) {
instance.spliceWaypoints(1, 1, new L.Routing.Waypoint(e.latlng, null, {}));
} else {
instance.spliceWaypoints(instance.getWaypoints().length, 0, new L.Routing.Waypoint(e.latlng, null, {}));
}
}
});
return instance;
};
const RoutingMachine = createControlComponent(CreateRoutineMachineLayer);
error :
g: React has detected a change in the order of Hooks called by ForwardRef(LeafComponent). This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
Previous render Next render
------------------------------------------------------
1. useContext useContext
2. useRef useRef
3. useContext useRef
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
..............
Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
I clearly doing something wrong here but I haven't found yet.
Thank you
Kind regards
Ok I found the good implementation :
const RoutingMachine: React.FC<RoutingMachineProps> = (props) => {
//const RoutineMachine = (props: any) => {
const geoService = new GeoLocalisationService();
const cartographyContext: CartographyContextType = React.useContext<CartographyContextType>(CartographyContext);
const [instance, setInstance] = React.useState<any>();
const [alreadyDisplayed, setAlreadyDisplayed] = React.useState(false);
const { orsOptions } = props;
const map = useMap();
//const instance = L.Routing.control({
React.useEffect(() => {
const instance = L.Routing.control({
router: new OpenRouteRouter(orsOptions),
lineOptions: {
styles: [{ color: "#3933ff", weight: 4 }],
extendToWaypoints: true,
missingRouteTolerance: 0
},
routeWhileDragging: true,
autoRoute: true,
geocoder: (L.Control as any).Geocoder.google({
apiKey: GOOGLE.googleMapApiKey,
}),
}).on('routesfound', (e) => {
const routes = e.routes;
cartographyContext.setElevationProfile(geoService.getElevationProfile(decodePolyline(routes[0].geometry, true)));
const summary: RouteSummary = {
ascent: routes[0].routeSummary.ascent,
descent: routes[0].routeSummary.descent,
distance: routes[0].routeSummary.distance,
estimatedDuration: routes[0].routeSummary.duration
}
cartographyContext.setRouteSummary(summary);
})
setInstance(instance);
instance.addTo(map);
}, []);
useMapEvents({
click: (e: L.LeafletMouseEvent) => {
if (instance) {
if (instance.getWaypoints().length === 2 && instance.getWaypoints()[0].latLng == null) {
instance.spliceWaypoints(0, 1, new L.Routing.Waypoint(e.latlng, null, {}));
} else if (instance.getWaypoints().length === 2 && instance.getWaypoints()[1].latLng == null) {
instance.spliceWaypoints(1, 1, new L.Routing.Waypoint(e.latlng, null, {}));
} else {
instance.spliceWaypoints(instance.getWaypoints().length, 0, new L.Routing.Waypoint(e.latlng, null, {}));
}
}
}
});
return null;
};
export default RoutingMachine;

Pagination Apollo Client 3 - Cache merges but does not render new results when paginating

I'd love to implement nested pagination within my application. I have been reading the docs and looking at several other examples but I just can't get this to work - any help is appreciated! Thanks!
React component:
I am clicking the button to run the fetchMore function provided by the useQuery hook (apollo). The network request is going through and the new products are merged into the cache... but no new products render on the page.
export const FilterableKit = () => {
const selectedKitId = useReactiveVar(selectedKitIdVar);
const [
getKitProducts,
{ data: getKitProductsData, loading: getKitProductsLoading, fetchMore },
] = useGetKitProductsLazyQuery();
useEffect(() => {
if (selectedKitId) {
getKitProducts({
variables: {
getKitsInput: {
_id: {
string: selectedKitId,
filterBy: "OBJECTID" as StringFilterByEnum,
},
},
getProductsInput: {
config: {
pagination: {
reverse: true,
limit: 3,
},
},
},
},
});
}
}, [getKitProducts, selectedKitId]);
const kitProducts = getKitProductsData?.getKits.data?.find(
(kit) => kit?._id === selectedKitId
)?.products.data;
const handleLoadMore = () => {
if (kitProducts && kitProducts?.length > 0) {
const remaining =
getKitProductsData?.getKits.data[0]?.products.stats?.remaining;
if (remaining && remaining > 0) {
const cursor =
kitProducts[kitProducts.length - 1] &&
kitProducts[kitProducts.length - 1]?.createdAt;
fetchMore({
variables: {
getProductsInput: {
config: {
pagination: {
reverse: true,
createdAt: cursor,
},
},
},
},
});
}
}
};
return (
<CContainer>
<KitItemCards products={kitProducts} loading={getKitProductsLoading} />
<CContainer className="d-flex justify-content-center my-3">
<CButton color="primary" className="w-100" onClick={handleLoadMore}>
Load More
</CButton>
</CContainer>
</CContainer>
);
};
Type Policies: I define the "Kit" typePolicy to merge products into the correct field.
export const cache: InMemoryCache = new InMemoryCache({
typePolicies: {
Kit: {
fields: {
products: {
keyArgs: false,
merge(existing = [] as Product[], incoming: GetProductsResponse) {
if (!incoming) return existing;
if (!existing) return incoming;
const { data: products, ...rest } = incoming;
let result: any = rest;
result = [...existing, ...(products ?? [])];
return result;
},
},
},
},
});
Thanks for any pointers in the right direction! Let me know if there is something else you'd like to see.

Vue3 composition API refactor computed favoritesRecipes

I am new to composition API with vue3. I have created that computed property and I would like to have that computed variable in a different file, I'm not sure if I should create a new component or I could achieve it from a js file.
Here is the component working (I did it with setup()):
export default {
name: "Recipes",
setup() {
const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
const favoritesRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter(item => {
return item.favorite;
});
}
return tempFavs;
...
});
...
}
return {
...toRefs(state),
favoriteRecipes
}
// end of setup
}
You can split it into two files
state.js
export const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
export const favoriteRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter(item => {
return item.favorite;
});
}
return tempFavs;
})
and recipes.vue
import { state, favoriteRecipes } from "state.js";
export default {
name: "Recipes",
setup() {
return {
...toRefs(state),
favoriteRecipes,
};
},
};
But this will make the state persistent, so if you have multiple components, they will all have the same favoriteRecipes and state values.
If you want them to be unique for each component...
state.js
export const withState = () => {
const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
const favoriteRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter((item) => {
return item.favorite;
});
}
return tempFavs;
});
return { state, favoriteRecipes };
};
and recipes.vue
import { withState } from "state.js";
export default {
name: "Recipes",
setup() {
const {state, favoriteRecipes} = withState()
return {
...toRefs(state),
favoriteRecipes,
};
},
};

Sort() not working

I'm having an issue with the sort() in ranking data from coinmarketcap api. With an ajax api call, sort works in returning an array with the right ranking. With an axios api call, seen below, it doesn't.
Here is my code using axios and vue.js:
let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;
let newApp = new Vue({
el: '#coinApp',
data: {
// data within an array
results: []
},
methods: {
getCoins: function() {
axios
.get(coinMarket)
.then((resp) => {
this.results = formatCoins(resp);
});
},
getColor: (num) => {
return num > 0 ? "color:green;" : "color:red;";
},
},
created: function() {
this.getCoins();
}
})
setInterval(() => {
newApp.getCoins();
},
updateInterval
);
function formatCoins(res) {
var coinDataArray = []
Object.keys(res.data).forEach(function(key) {
coinDataArray.push(res.data[key])
})
coinDataArray.sort(function(a,b) {
return a.rank > b.rank
})
console.log(coinDataArray)
}
Where am I going wrong?
If you look into the data responded by https://api.coinmarketcap.com/v2/ticker/?limit=10, you will find the data you need is under res.data.data, not res.data.
So within the function=formatCoins, replace res.data with res.data.data, then works.
Vue.config.productionTip = false
let coinMarket = 'https://api.coinmarketcap.com/v2/ticker/?limit=10'
let updateInterval = 60 * 1000;
function formatCoins(res) {
var coinDataArray = []
Object.keys(res.data.data).forEach(function(key) {
coinDataArray.push(res.data.data[key])
})
coinDataArray.sort(function(a,b) {
return a.rank - b.rank
})
return coinDataArray
}
let newApp = new Vue({
el: '#coinApp',
data: {
// data within an array
results: []
},
methods: {
getCoins: function() {
axios
.get(coinMarket)
.then((resp) => {
this.results = formatCoins(resp);
});
},
getColor: (num) => {
return num > 0 ? "color:green;" : "color:red;";
},
},
created: function() {
this.getCoins();
}
})
setInterval(() => {
newApp.getCoins();
},
updateInterval
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="coinApp">
<div v-for="(record, index) in results" :key="index">
{{index}} - {{record.name}}: {{record.rank}}
</div>
</div>

Resources