pinia 快速使用

pinia 快速使用

详细文档请访问 pinia

安装

使用 npm

shell
npm i pinia

使用 yarn

shell
yarn add pinia

使用 pnpm

shell
pnpm i pinia

在 vue 中使用

ts
import { createPinia } from "pinia"
import { createApp } from "vue"

const app = createApp()
const pinia = createPinia()
app.use(pinia)
app.mount("#app")

定义一个 Store

导出的 store 函数名一般使用 use 开头

ts
import { defineStore } from "pinia"
// 第一个参数在全局store中的唯一id
export const useUserStore = defineStore("user", {})

在页面中使用 store

html
<script lang="ts" setup>
import { useUserStore } from "@/store/model/userStore"
const userStore = useUserStore()
// 可以使用userStore.xx来访问store中的内容
</script>

or

html
<script lang="ts" setup>
import { useUserStore } from "@/store/model/userStore"
import { storeToRefs } from "pinia"
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
</script>

State

ts
import { defineStore } from "pinia"
export const useUserStore = defineStore("user", {
    state: () => {
        return {
            userInfo: null,
        }
    },
})

在页面中访问 state

可以直接写入/读取状态

js
import { useUserStore } from "@/store/model/userStore"
const userStore = useUserStore()
userStore.userInfo = { name: "wxw", age: 23 }
console.log(userStore.userInfo)

重置状态

js
import { useUserStore } from "@/store/model/userStore"
const userStore = useUserStore()
userStore.$reset()

Getters

可以等同于 vue 中的计算属性

ts
import { defineStore } from "pinia"
export const useUserStore = defineStore("user", {
    state: () => {
        return {
            userInfo: null,
        }
    },
    getters: {
        getUserInfo() {
            return this.userInfo
        },
    },
})

在页面中使用 getter

getter 是属性,访问时不需要使用函数的方式来访问

html
<script lang="ts" setup>
import { useUserStore } from "@/store/model/userStore"
const userStore = useUserStore()

setTimeout(() => {
    userStore.userInfo = { name: "wxw", age: 23 }
}, 3000)
</script>

<template>
    <div>{{ userStore.getUserInfo }}</div>
</template>

Actions

相当于组件的方法(vue2 中的 methods)

在组件中使用

vue
<script lang="ts" setup>
import { useUserStore } from "@/store/model/userStore"
const userStore = useUserStore()
function setUser() {
    userStore.setUserInfo({ name: "wxw", age: 23 })
}
</script>

<template>
    <button @click="setUser">
        设置用户信息
    </button>
    <div>{{ userStore.getUserInfo }}</div>
</template>

Plugins

持久化插件

pinia-plugin-persistedstate


Vue3 响应式系统
vite使用

评论区

评论加载中...