学习vue第三天

状态管理Pinia

  • Pinia是Vue的存储库,它允许跨组件/ 页面共享状态
  • pinia中的store是模块化的,根据不同的状态划分不同的模块

  • 创建ProductStore 用于存储商品列表状态
// src/stores/ProductStore.js
import { defineStore } from "pinia"
import products from "@/data/products.json"

export const useProductStore = defineStore("ProductStore",{
state: () => {
  return {
    products,
    test:"test"
   }
}
})


// src/App.vue

import {useProductStore} from "./stores/ProductStore"
useProductStore();
  ![](https://secure2.wostatic.cn/static/eFTxRzjqujnMLGknMZ86bQ/image.png?auth_key=1744797510-gSpQr9Y1vBHhNjasv4xGSK-0-8b8ceac14e0f5c6285b225ca6343428b)
  • 组件获取状态
// App.vue
import { useProductStore } from "./stores/ProductStore";
import { storeToRefs } from "pinia";
useProductStore();
const { products, test } = storeToRefs(useProductStore());
const productStore = useProductStore();
productStore.fill();


// src/stores/ProductStore.js

export const useProductStore = defineStore("ProductStore",{
state: () => {
  return {
    products,
    test:"test"
   }
  },
  actions:{
    async fill() {
       this.products = (await import("@/data/products.json")).default;
    }
  }
})

  • 将商品加入购物车
// src/stores/CartStore.js
import {defineStore} from "pinia";
export const useCartStore = defineStore("CartStore",{
  state: () => {
    return {
      items:[],
    }
  },
  actions: {
    addItems(count,product){
      for (let i = 0; i < count; i++){
        this.items.push(product)
      }
    }
  }
})


// App.vue
<script setup>
  import { useCartStore } from "@/stores/CartStore";
  const cartStore = useCartStore();
</script>

<template>
  <ProductCard @addToCart="cartStore.addItems($event, product)"/>
</template>