日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

pinia

發(fā)布時(shí)間:2023/12/15 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pinia 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
  • 安裝npm i pinia
  • 導(dǎo)入import { createPinia} from 'pinia'
  • 注冊(cè) app.use(createPinia())

使用

  • index.ts
/*** 注冊(cè)容器*/ import { defineStore } from 'pinia'// 定義容器 // 參數(shù)1:容器的 id,必須唯一,可以理解為就是有名字的模塊 // 參數(shù)2:選項(xiàng)對(duì)象 export const useMainStore = defineStore('main', {// 類似組件的 data,用來(lái)存儲(chǔ)全局狀態(tài)的// 注意:// 1. 必須是函數(shù),因?yàn)槿萜饕惨嫒?SSR 服務(wù)端渲染,避免多個(gè)請(qǐng)求數(shù)據(jù)交叉污染// 2. 必須是箭頭函數(shù),這是為了 ts 類型推斷state: () => {return {count: 100}},// 類似組件的 computed 計(jì)算屬性,也有緩存功能// 參數(shù)1 就是 state 對(duì)象getters: {counter10 (state) {return state.count + 10}// 也可以在 getters 中使用 this,但是這種情況下必須手動(dòng)標(biāo)記 getter 的返回值類型// counter10 (): number {// return this.count + 10// }},// 類似組件的 methods,主要用來(lái)封裝操作邏輯// 在其中使用 this 操作容器數(shù)據(jù),同步異步都支持actions: {incrementCount (a: string, b: number) {// this.count++setTimeout(() => {this.count++}, 1000)}} })
  • counter.vue
<template><h2>Counter A</h2><p>{{ mainStore.count }}</p><p>{{ mainStore.counter10 }}</p><p><button @click="handleChangeState">修改 state 數(shù)據(jù)</button></p> </template><script setup lang="ts"> import { useMainStore } from '../store/index'// 調(diào)用得到容器對(duì)象 const mainStore = useMainStore()const handleChangeState = () => {// 方式一:// mainStore.count++// 方式二:批量更新// mainStore.$patch({// count: mainStore.count + 1// })// 方式三:在 action 中修改// Vuex 中調(diào)用 mutation 得 commit,調(diào)用 action 得 dispatch// action 同步異步操作都支持mainStore.incrementCount('a', 10) } </script>
  • ProductList.vue
<template><ul><li v-for="item in all">{{ item.title }} - {{ item.price }}<br /><button:disabled="!item.inventory"@click="cartStore.addProductToCart(item)">添加到購(gòu)物車</button></li></ul> </template><script setup lang="ts"> import { storeToRefs } from 'pinia' import { useProductsStore } from '../store/products' import { useCartStore } from '../store/cart'const productsStore = useProductsStore() const cartStore = useCartStore()// 異步加載更新數(shù)據(jù) productsStore.loadAllProducts()// 數(shù)據(jù)解構(gòu) // 注意:這種寫法是有問(wèn)題的,不是響應(yīng)式的,只能拿到一次性的數(shù)據(jù) // const { all } = productsStore// 響應(yīng)式解構(gòu)處理,內(nèi)部其實(shí)是被 ref 包裹了 const { all } = storeToRefs(productsStore)console.log(all.value) </script>
  • products.ts
/*** 注冊(cè)容器*/ import { defineStore } from 'pinia' import { getProducts, IProduct } from '../api/shop'export const useProductsStore = defineStore('products', {state: () => {return {all: [{ id: 1, title: 'xxx', price: 10, inventory: 100 }] as IProduct[] // 所以商品列表}},getters: {},actions: {async loadAllProducts () {const ret = await getProducts()this.all = ret},async decrementProduct (product: IProduct) {const p = this.all.find(item => item.id === product.id)if (p) {p.inventory--}}} })
  • ShoppingCart
<template><div class="cart"><h2>你的購(gòu)物車</h2><p><i>請(qǐng)?zhí)砑右恍┥唐返劫?gòu)物車.</i></p><ul><li v-for="item in cartStore.cartProducts">{{ item.title }} - {{ item.price }} x {{ item.quantity }}</li><!-- <li>商品名稱 - 商品價(jià)格 x 商品數(shù)量</li><li>商品名稱 - 商品價(jià)格 x 商品數(shù)量</li> --></ul><p>商品總價(jià): {{ cartStore.totalPrice }}</p><p><button @click="cartStore.checkout">結(jié)算</button></p><p v-show="cartStore.checkoutStatus">結(jié)算{{ cartStore.checkoutStatus }}.</p></div> </template><script setup lang="ts"> import { useCartStore } from '../store/cart'const cartStore = useCartStore() </script>
  • shop.ts
export interface IProduct {id: number // 唯一標(biāo)識(shí)title: string // 名稱price: number // 價(jià)格inventory: number // 庫(kù)存 }const _products: IProduct[] = [{ id: 1, title: 'iPad 4 Mini', price: 500.01, inventory: 2 },{ id: 2, title: 'H&M T-Shirt White', price: 10.99, inventory: 10 },{ id: 3, title: 'Charli XCX - Sucker CD', price: 19.99, inventory: 5 } ]/*** 獲取商品列表*/ export const getProducts = async () => {await wait(100)return _products }/*** 訂單結(jié)算*/ export const buyProducts = async () => {await wait(100)return Math.random() > 0.5 }async function wait(delay: number) {return new Promise((resolve) => setTimeout(resolve, delay)) }
  • cart.ts
import { defineStore } from 'pinia' import { IProduct, buyProducts } from '../api/shop' import { useProductsStore } from './products' // 合并IProduct,但是去除掉inventory type CartProduct = {quantity: number } & Omit<IProduct, 'inventory'>export const useCartStore = defineStore('cart', {state: () => {return {cartProducts: [] as CartProduct[],checkoutStatus: null as null | string // 結(jié)算狀態(tài)}},getters: {totalPrice (state) {return state.cartProducts.reduce((price, item) => {return price + item.quantity * item.price}, 0)}},actions: {addProductToCart(product: IProduct) {this.checkoutStatus = null// this.cartProducts.push(product)// 商品是否有庫(kù)存if (product.inventory <= 0) {return}// 購(gòu)物車中是否已有該商品const item = this.cartProducts.find(p => p.id === product.id)if (item) {// 如果有,則讓已有商品的數(shù)量 +1item.quantity++} else {// 如果沒(méi)有,則新增this.cartProducts.push({id: product.id,title: product.title,price: product.price,quantity: 1 // 剛加到購(gòu)物車的商品的數(shù)量肯定是 1 個(gè)})}// 更新商品的庫(kù)存const productsStore = useProductsStore()productsStore.decrementProduct(product)},async checkout () {this.checkoutStatus = null // 充值結(jié)算狀態(tài)const ret = await buyProducts()if (ret) {this.checkoutStatus = '成功'this.cartProducts = [] // 清除購(gòu)物車數(shù)據(jù)} else {this.checkoutStatus = '失敗'}}} })

總結(jié)

以上是生活随笔為你收集整理的pinia的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。