一、入门案例
1、安装
npm i pinia -S
2、注册插件
//main.ts
import { createPinia } from 'pinia'
app.use(createPinia())
3、创建store/countStore.ts
import { defineStore } from "pinia";
const useCounterStore = defineStore('counterStore',{
state(){
return{
count:0
}
},
actions:{
add(){
this.count++
}
}
})
export default useCounterStore
4、使用App.vue
<template>
<div>
{{ count }}
<button @click="add">点我加一</button>
</div>
</template>
<script setup lang='ts'>
import useCounterStore from './store/countStore';
import { storeToRefs } from 'pinia';
const counterStore = useCounterStore()
const {count} = storeToRefs(counterStore) //storeToRefs让其成为响应式
const add = counterStore.add
</script>
二、购物车案例
1、新建一个列表的productStore.js的文件
import { defineStore } from "pinia";
import axios from 'axios'
const useProductStore = defineStore('productStore',{
state(){
return{
products:[
]
}
},
actions:{
async loadDate(){
let res = await axios.get("http://localhost:9000/data")
this.products = res.data
console.log(res);
}
}
})
export default useProductStore
2、购物车的商品cartStore.js
import { defineStore } from "pinia";
const useCartStore = defineStore("cartStore", {
state() {
return {
carts: [],
};
},
actions: {
add(product) {
const pro = this.carts.find((value) => {
console.log(value);
return product.id === value.id;
});
product.inventory--
if (pro) {
pro.quality++;
} else {
this.carts.push({ ...product, quality: 1 });
}
},
},
getters:{
total(){
return this.carts.reduce((pre,cur)=>{
return pre += cur.quality * cur.price
},0)
}
}
});
export default useCartStore;
3.使用App.vue
<template>
<div>
<h1>产品列表</h1>
<hr>
<ul>
<li v-for="i in products">
{{ i.name }} -- ¥{{ i.price }}<button @click="cartStore.add(i)" :disabled="i.inventory <= 0">放入购物车</button>
</li>
</ul>
<h1>购物车</h1>
<hr>
<ul>
<li v-for="i in carts">
姓名:{{ i.name }} ---价格:{{ i.price }} ----- 数量:{{ i.quality }} ---商品总价:{{ i.quality * i.price }}
</li>
</ul>
<h1>总价格:{{ total }}</h1>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from "pinia";
import { onMounted } from "vue";
import useProductStore from "./store/productorStore"
import useCartStore from "./store/cartStore"
const productStore = useProductStore()
const cartStore = useCartStore()
const { products } = storeToRefs(productStore)
const { carts,total } = storeToRefs(cartStore)
onMounted(()=>{
productStore.loadDate()
})
</script>
<style scoped lang='scss'>
</style>
三、模拟后台接口
1.新建一个json文件
{
"data":[
{
"id":1,
"name":"iphone12",
"price":12000,
"inventory":3
},
{
"id":2,
"name":"小米10",
"price":3000,
"inventory":10
},
{
"id":3,
"name":"华为",
"price":5000,
"inventory":7
}
]
}
2、安装json-server
npm i json-server -g
3、使用
json-server ./src/data/api.json -p 9000