 
      
     一. Pinia安装
    
命令安装
yarn add pinia
# or with npm
npm install pinia
     二. 使用Pinia
    
1. main.js引入并挂载
import { createPinia } from 'pinia'
 
app.use(createPinia())2. 在store包下建index.js
 
      写入
import { defineStore } from 'pinia'
 
//1.定义并导出容器
//参数1:容器的ID.必须唯一,将来Pinia会把所有的容器挂载到根容器
//参数2:选项对象
//返回值:一个函数,调用得到容器实例
export const useStore = defineStore('storeId', {
    /**
     *  类似于组建的data,用来储存全局状态
     * 1.必须是函数,这样为了在服务端渲染的时候避免交叉请求导致的数据状态太污染
     * 2.必须是箭头函数,为了更好的TS类型推导
     */
  state: () => {
    return {
      username:'张三',
      phone:'1734985035',
      createTime:'2004-05-12',
      updateTime:'2023-01-04',
    }
  },
  /**
   * 类似于组件的computed,用来封装计算属性,有缓存的功能
   */
  getters:{},
  /**
   * 类似于组建的methods,封装业务逻辑,修改state
   */
  actions:{}
})3.然后在页面中引入store,使用pinia。
<template>
  <h3>pinia</h3>
  <!-- 在页面中直接使用就可以了 -->
  <p>pinia 中的信息: {{store.username}} --- {{store.phone}}</p>
  <!-- 下面这种调用方法也可以 -->
  <p>{{createTime}}<p>
</template>
<script setup>
  // 首先需要引入一下我们刚刚创建的store
  import  { useStore }  from '../store';
  // 因为是个方法,所以我们得调用一下
  const store = useStore();
  console.log(store)
  let {username,phone,createTime,updateTime} = store
</script>
<style scoped>
</style>
输出信息如下:
 
      
     
      页面刷新
     
     后,数据会重置,安装类似vuex- persistdstate的pinia插件解决。
    
     三.持久化存储
    
- 
安装插件
 
npm install pinia-persistedstate-plugin2. 插件如果放在全局维护起来比较差,所以对之前的main.js进行更改,改回引用store文件夹
import store from './store'
app.use(store)- 
 原本的
 
 store/
 
 index.js划分为user模块改名为user.js,store/index.js中内容更改更改
 
 
import { createPinia } from "pinia";
//引入插件
import { createPersistedState } from "pinia-persistedstate-plugin";
const store = createPinia();
//使用插件
store.use(createPersistedState());
export { store };
Vuex与Pinia的区别:
- 
支持选项式api和组合式api写法 
- 
pinia没有mutations,只有: state、getters、actions 
- 
pinia分模块不需要modules(之前vuex分模块需要modules) 
- 
TypeScript支持很好 
- 
自动化代码拆分 
- 
pinia体积更小(性能更好) 
- 
pinia可以直接修改state数据 
参考资料:
 
版权声明:本文为m0_62811051原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
