在vue3中,pinia仓库的基本使用

1.安装

npm install pinia

2.引入(路径:vue3的main.js里)

// main.js
import { createPinia } from "pinia"
const app = createApp(App)
app.use(createPinia())
app.mount("#app")

 3.配置store.js(需要手动创建一个js文件,里面代码如下:)

import { defineStore } from "pinia"
export const useStore = defineStore('counter', {
     state: () => ({
         count: 1,
         data: {
         name: 'Franky',
         age: 30
     }
 }),
 actions: {
     update(name, age, count) {
     // 通过this访问state,赋值的⽅式直接修改
     this.data.name = name
     this.data.age = age
 
     // 还可以通过$patch同时修改多个值
     this.$patch({
         data: { name, age },
         count
         })
     }
 }
})

4.在组件中使用

<template>
     <div>
        {
   
   {store.data.name}}
    </div>
</template>
<script setup>
 import { useStore } from '@store/store.js'
 const store = useStore()
 // 取数据 store.data.name
 // 修改数据 store.update('Tom', 33, 10)
</scrip