跳至主要內容

状态管理pinia

shenjianZvuepinia约 185 字大约 1 分钟

Pinia

集中式状态管理

安装

npm i pinia

main.ts

import {createApp} from 'vue'
import App from './App.vue'
// 第一步:引入pinia
import {createPinia} from 'pinia'

const app = createApp(App)
// 第二步:创建pinia
const pinia = createPinia()
// 第三步:安装pinia
app.use(pinia)
app.mount('#app')

Count.vue

<template>
    <h2>{{ countStore.sum }}</h2>
</template>

<script setup lang="ts" name="Count">
  import { ref,reactive } from "vue";
  import {useCountStore} from '@/store/count'

  const countStore = useCountStore()
</script>

操作pinia的数据

  • 直接修改数据
  • $patch({}) 传入一个对象,改变对应的变量
  • actions 定义的函数进行修改

storeToRefs

拿到store中的属性的ref对象

<template>
    <h2>{{ countStore.sum }}</h2>
</template>

<script setup lang="ts" name="Count">
  import { ref,reactive } from "vue";
  import {useCountStore} from '@/store/count'

  const countStore = useCountStore()
  let {sum,sss} = storeToRefs(countStore)
</script>

getters

$subscribe