如何在应用程序首次加载时在Vue中加载存储

huangapple go评论66阅读模式
英文:

How to load the store in vue when the app first loads

问题

我想在应用程序加载时调用getProducts。我能够在Vue2中实现这一点,但不确定如何在Vue的新组合API版本中实现。请问有人可以建议我如何做到这一点吗?

英文:

I am trying to load products from my pinia store when my Vue app first loads.

This is my app.js

import {createApp} from "vue";
import App from "./App.vue";
import router from "./Router/index";
import { createPinia } from "pinia";

createApp(App)
    .use(router)
    .use(createPinia())
    .mount("#app")

And this is my store:

import { defineStore } from "pinia";
import axios from "axios";

const state = {
    cart: [],
    order: {},
    customer: {},
    loading: true,
    error: null,
    products: [],
};

export const useCartStore = defineStore("shopState", {
    state: () => state,
    actions: {
        async getProducts() {
            try {
                this.loading = true;
                const response = await axios.get("/api/product");
                this.products = response.data.data;
                this.loading = false;
            } catch (error) {
                this.error = error;
            }
        },
        addToCart({ item }) {
            const foundProductInCartIndex = this.cart.findIndex(
                (cartItem) => item.slug === cartItem.slug
            );

            if (foundProductInCartIndex > -1) {
                this.cart[foundProductInCartIndex].quantity += 1;
            } else {
                item.quantity = 1;
                this.cart.push(item);
            }
        },
        removeProductFromCart({ item }) {
            this.cart.splice(this.cart.indexOf(item), 1);
        },
        clearCart() {
            this.cart.length = 0;
        },
        clearCustomer() {
            this.customer = {};
        },
        clearOrder() {
            this.order = {};
        },
        updateCustomer(customer) {
            this.customer = customer;
        },
        updateOrder(order) {
            this.order = order;
        },
        getSingleProduct(slug) {
            return this.products.find((product) => product.slug === slug);
        },
    },
    getters: {
        getCartQuantity() {
            return this.cart.reduce(
                (total, product) => total + product.quantity,
                0
            );
        },
        getOrderDetails() {
            return this.order;
        },
        getCartContents() {
            return this.cart;
        },
        getCustomer() {
            return this.customer;
        },
        getCartTotal() {
            return this.cart.reduce(
                (total, product) => total + product.price * product.quantity,
                0
            );
        },
    },
    persist: true,
});

I would like to call getProducts when the app loads. I am able to do this using Vue2 but not sure how to do this with the new composition API version of Vue. Please can someone advise how I can do this?

答案1

得分: 1

如果你想在应用程序加载后加载产品,你可以在组合 API 中使用 onMounted() 钩子。

在你想加载产品的组件中:

<script setup>
import { onMounted } from 'vue';
import { useCartStore } from '../stores/storeName.js';
const store = useCartStore();
onMounted(() => {
  store.getProducts();
});
</script>

注意:我在这里使用了 <script setup>。但如果你使用 setup() 钩子,你需要手动返回该函数。

参考链接:https://vuejs.org/api/composition-api-lifecycle.html#onmounted

如果你要加载产品,可以在应用程序加载后使用组合 API 中的 onMounted() 钩子。

英文:

If you want to load the products once the app is loaded, you can use the onMounted() hook in the composition API.

https://vuejs.org/api/composition-api-lifecycle.html#onmounted

On the component where you want to load the products:

<script setup>
import { onMounted } from 'vue';
import { useCartStore } from '../stores/storeName.js';
const store = useCartStore()
onMounted(() => {

store.getProducts()
})
</script>

Note: I'm using <script setup> here. But if you're using the setup() hook you need to manually return the function

https://vuejs.org/api/composition-api-setup.html

huangapple
  • 本文由 发表于 2023年2月19日 07:09:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定