Work With Pinia
Pinia is a store library for Vue, it allows you to share a state across components/pages. If you are familiar with the Composition API, you might be thinking you can already share a global state with a simple export const state = reactive({}). This is true for single page applications but exposes your application to security vulnerabilities if it is server side rendered.
How to use Pinia?
For Example:
cart.js
This is what using Pinia looks like in terms of API. You start by creating a store:
export const useCartStore = defineStore("cart-store", () => {
var cart = ref([]);
const GetCartDataFromApi = async () => {
let { data, error } = await useFetch("cart", {
baseURL: BaseUrl,
headers: GetHeaders(),
method: "get",
});
if (error.value) {
alert("Cart is empty")
} else {
cart.value = data?.value?.items;
}
};
Shop >> Cart >> Product.vue
Use it in a component:
import { useCartStore } from "@/store/cart"
let { cart, CartTotal } = storeToRefs(useCartStore())
function cartAction(item) {
useCartStore().RemoveFromCart({ CartItem: item })
}