Pinia 学习心得与应用

Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3

安装 Pinia

安装 pinia 和持久化插件pinia-plugin-persistedstate

yarn add pinia
yarn add pinia-plugin-persistedstate
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.mount('#app')

js

src目录下创建stores文件夹
创建文件counter.js

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      // 所有这些属性都将自动推断其类型
      count: 0,
      name: 'Eduardo',
      isAdmin: true,
    }
  },
  getters: {
    doubleCount: (state: any) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    },
    randomizeCounter() {
      this.count = Math.round(100 * Math.random())
    },
  },
  persist:{
     // 存储的 key, 默认是 defineStore 的第一个参数
    // key: "A",
    // 存储路径
    storage: localStorage,
    // 指定内容
    paths: ["count","name"],
  }
})

使用

<script setup lang="ts">
import { useCounterStore } from './../stores/counter'
const counter  = useCounterStore()

function resetStore(){
  counter.$reset()
}

</script>

<template>
  <p>this is {{ counter.count }}-- {{ counter.doubleCount }}</p>
  <input type="text" v-model="counter.count" />

  <button @click="counter.increment">increment</button>
  <button @click="resetStore">resetStore</button>
</template>

ts

代码 :https://gitee.com/paipaicui/PiniaTest

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值