pinia的使用

69 阅读1分钟

为什么要使用 Pinia?(pinia.web3doc.top/introductio…)

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 如果您熟悉 Composition API,您可能会认为您已经可以通过一个简单的 export const state = reactive({}). 这对于单页应用程序来说是正确的,但如果它是服务器端呈现的,会使您的应用程序暴露于安全漏洞。 但即使在小型单页应用程序中,您也可以从使用 Pinia 中获得很多好处:

  • dev-tools 支持

    • 跟踪动作、突变的时间线
    • Store 出现在使用它们的组件中
    • time travel 和 更容易的调试
  • 热模块更换

    • 在不重新加载页面的情况下修改您的 Store
    • 在开发时保持任何现有状态
  • 插件:使用插件扩展 Pinia 功能

  • 为 JS 用户提供适当的 TypeScript 支持或 autocompletion

  • 服务器端渲染支持

1、安装

npm install pinia

2、在vue3中main.js引用

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' //数据持久化

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
app.use(createPinia())

3、 在src目录创建store目录再创建counter.js


import { defineStore } from 'pinia'
// 1. 创建store
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    double() {
      return this.count * 2
    },
  },
  actions: {
    increment() {
      this.count=this.count+1
    },
    incrementAsync() {
      setTimeout(() => {
        this.count=this.count+1
      }, 1000)
    },
  },
  persist: {
    // 修改存储中使用的键名称,默认为当前 Store的 id
 
    // 修改为 sessionStorage,默认为 localStorage
    storage: window.localStorage,
    // 部分持久化状态的点符号路径数组,[]意味着没有状态被持久化(默认为undefined,持久化整个状态)
    paths: ['count'],
  }
})

export default useCounterStore

4 在页面中调用及展示

<script setup>
 import { toRefs } from "vue"; 
 import { storeToRefs } from "pinia";
 import useCounterStore from "../store/counter"
  
  
  这里有两种写法,一种直接从仓库获取,一种通过响应式解构,
  1const counterStore= useCounterStore();
  2.  const { count,double} = storeToRefs(counterStore);//或者 const { count,double} = toRefs(counterStore)

  // 更改状态、触发更新的函数
  function increment() {
    counterStore.increment();
  }
 
  </script>
<template>
  <div class="about">
     1、一种直接从仓库获取
    <button @click="increment">点击了:{{counterStore.count }} 次</button>
    <div>getter:{{counterStore.double}}次</div>
    2、解构
     <button @click="increment">点击了:{count }} 次</button>
    <div>getter:{{double}}次</div>
  </div>
</template>