比较

优点

安装

npm install pinia

配置

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
import axios from 'axios'
import { createPinia } from 'pinia'

const app = createApp(App)
app.config.globalProperties.$axios = axios
app
  .use(router)
  .use(createPinia())
  .mount('#app')

定义

import { defineStore } from 'pinia'

interface IUser {
  name: string
  age: number
}
export const useUserStore = defineStore('user', {
  state(): IUser {
    return {
      name: '',
      age: 0,
    }
  },
  getters: {},
  actions: {
    updateUser(user: IUser) {
      this.name = user.name
      this.age = user.age
    },
  },
})

使用

state

基本使用

<template>
  <div>userAge: {{ user.age }}</div>
</template>
<script setup lang="ts">
import { useUserStore } from '../pinia/user'
const user = useUserStore()
setTimeout(() => {
  user.updateUser({
    name: 'Sherry',
    age: 30
  })
}, 500)
</script>

storeToRefs 使解构能响应式