提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
目录
1、数据仓库
(1)先下载npm install pinia
(2)在vite里面的main.js里面去配置
import { createPinia } from 'pinia' let app=createApp(App) app.use(createPinia())
(3)然后写写个文件store并在index.js写入代码:
import { defineStore } from 'pinia' export const useCar = defineStore("car", { // 这里易错语法:如果箭头函数直接指向返回值的,记得把返回的对象用小括号括起来 state:()=>{ return {msg:"carhello 仓库的数据"} } })
(4)然后在组件或者接口里面的使用:
<template> <div> <h1>page1</h1> <p>{{store.msg}}</p> </div> </template> <script setup> import {useCar} from "../store/index.js" let store=useCar() console.log(store.msg) </script>
1.1修改仓库的方法
(1)单独修改
(2)批量修改
2、订阅修改
可以通过 store 的 $subscribe() 方法查看状态及其变化,通过patch修改状态时就会触发一次
3.Getter和Actions
Getter :完全等同于 Store 状态的 计算值。 它们可以用
defineStore()
中的getters
属性定义。 他们接收“状态”作为第一个参数以鼓励箭头函数的使用
Actions:在pinia中没有提供mutaion 因为Actions就够了(它可以异步同步的统一修改状态)
之所以提供这个功能 就是为了项目中的公共修改状态的业务统一。
在store文件里面的index.js(pinia里面)去写入: