目录
读state
state?
?写state
?方式一:【修改单个数据时推荐】
?方式二:$patch({})? ?【不推荐】
方式三:$patch((state)=>{})? ?【修改多个数据时推荐】
方式四:$state
?方式五:action? 【修改多个数据时推荐】?
action
同步
异步
getters
内置api函数
$reset()
$subscribe
$onAction
下载:
npm i -S pinia
main.js中引入pinia:?

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from "pinia"
createApp(App).use(createPinia()).mount('#app')
读state


import { defineStore } from "pinia";
export const useTestStore = defineStore('Test', {
state: () => {
return {
user: '张三',
age: 33
}
},
getters: {
},
actions: {
}
})
state?
?写state
?方式一:【修改单个数据时推荐】

?方式二:$patch({})? ?【不推荐】

方式三:$patch((state)=>{})? ?【修改多个数据时推荐】

方式四:$state

?方式五:action? 【修改多个数据时推荐】?

state解构-storeToRefs
需要使用storeToRefs()才能是响应式

<template>
<div>
<p>user: {{ user }}</p>
<p>age: {{ age }}</p>
<p>Test.user {{ Test.user }}</p>
<p>Test.age {{ Test.age }}</p>
</div>
<button @click="change">修改</button>
</template>
<script setup>
import { storeToRefs } from "pinia";
import { useTestStore } from "./store";
const Test = useTestStore();
let { user, age } = storeToRefs(Test);
function change() {
user.value = "李四";
age.value++;
}
</script>
<style scoped>
</style>
?
action
同步

异步

getters

内置api函数
$reset()
state重置为初始化状态

$subscribe
state中的值一改变就会触发


$onAction
$onAction函数接受一个回调函数,该回调函数内部的代码会先于actions函数调用前执行
?after钩子函数会在actions中的函数被调用后执行
 ?
|