首页 > 其他分享 >Pinia

Pinia

时间:2023-11-17 16:14:41浏览次数:22  
标签:const name state user Pinia data store

Pinia 优势

Pinia.js 是新一代的状态管理器,由 Vue.js 团队中成员所开发的,因此也被认为是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的项目中使用也是备受推崇。

Pinia.js 有如下特点:
完整的 typescript 的支持;
足够轻量,压缩后的体积只有 1.6kb;
去除 mutations,只有 state,getters,actions(这是最喜欢的一个特点);
actions 支持同步和异步;
没有模块嵌套,只有 store 的概念,store 之间可以自由使用,更好的代码分割;
无需手动添加 store,store 一旦创建便会自动添加;

Pinia 基本使用

创建 Store

新建 src/store 目录并在其下面创建 index.ts,导出 store

// src/store/index.ts
import { createPinia } from "pinia";
const store = createPinia();
export default store;

在 main.ts 中引入并使用。

// src/main.ts

import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";

const app = createApp(App);
app.use(store);

State

定义 State

在 src/store 下面创建一个 user.ts

//src/store/user.ts

import { defineStore } from "pinia";

export const useUserStore = defineStore({
  id: "user", // id必填,且需要唯一
  state: () => {
    return {
      name: "张三",
    };
  },
});

获取 state

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

<script lang="ts" setup>
import { useUserStore } from "@/store/user";

const userStore = useUserStore();
</script>

也可以结合 computed 获取。

const name = computed(() => userStore.name);

state 也可以使用解构,但使用解构会使其失去响应式,这时候可以用 pinia 的 storeToRefs。

import { storeToRefs } from "pinia";
const { name } = storeToRefs(userStore);

修改 state

可以像下面这样直接修改 state

userStore.name = "李四";

但一般不建议这么做,建议通过 actions 去修改 state,action 里可以直接通过 this 访问。

export const useUserStore = defineStore({
  id: "user",
  state: () => {
    return {
      name: "张三",
    };
  },
  actions: {
    updateName(name) {
      this.name = name;
    },
  },
});
<script lang="ts" setup>
  import { useUserStore } from "@/store/user";

  const userStore = useUserStore();
  userStore.updateName("李四");
</script>

Getters

export const useUserStore = defineStore({
  id: "user",
  state: () => {
    return {
      name: "张三",
    };
  },
  getters: {
    fullName: (state) => {
      return state.name + "丰";
    },
  },
});
userStore.fullName; // 张三丰

Actions

异步 action

action 可以像写一个简单的函数一样支持 async/await 的语法,让愉快的应付异步处理的场景。

export const useUserStore = defineStore({
  id: "user",
  actions: {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd);
      return data;
    },
  },
});

action 间相互调用

action 间的相互调用,直接用 this 访问即可。

export const useUserStore = defineStore({
  id: "user",
  actions: {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd);
      this.setData(data); // 调用另一个 action 的方法
      return data;
    },
    setData(data) {
      console.log(data);
    },
  },
});

在 action 里调用其他 store 里的 action 也比较简单,引入对应的 store 后即可访问其内部的方法了。

// src/store/user.ts
import { useAppStore } from "./app";
export const useUserStore = defineStore({
  id: "user",
  actions: {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd);
      const appStore = useAppStore();
      appStore.setData(data); // 调用 app store 里的 action 方法
      return data;
    },
  },
});
// src/store/app.ts
export const useAppStore = defineStore({
  id: "app",
  actions: {
    setData(data) {
      console.log(data);
    },
  },
});

数据持久化

插件 pinia-plugin-persist 可以辅助实现数据持久化功能。

安装

npm i pinia-plugin-persist --save

使用

// src/store/index.ts
import { createPinia } from "pinia";
import piniaPluginPersist from "pinia-plugin-persist";

const store = createPinia();
store.use(piniaPluginPersist);

export default store;

接着在对应的 store 里开启 persist 即可。

export const useUserStore = defineStore({
  id: "user",

  state: () => {
    return {
      name: "张三",
    };
  },

  // 开启数据缓存
  persist: {
    enabled: true,
  },
});

image
数据默认存在 sessionStorage 里,并且会以 store 的 id 作为 key。

自定义 key

也可以在 strategies 里自定义 key 值,并将存放位置由 sessionStorage 改为 localStorage。

persist: {
  enabled: true,
  strategies: [
    {
      key: 'my_user',
      storage: localStorage,
    }
  ]
}

iamge

持久化部分 state

默认所有 state 都会进行缓存,可以通过 paths 指定要持久化的字段,其他的则不会进行持久化。

state: () => {
  return {
    name: '张三',
    age: 18,
    gender: '男'
  }
},

persist: {
  enabled: true,
  strategies: [
    {
      storage: localStorage,
      paths: ['name', 'age']
    }
  ]
}

标签:const,name,state,user,Pinia,data,store
From: https://www.cnblogs.com/wp-leonard/p/17838982.html

相关文章

  • vue pinia sessionstorage 数据存储不上的原因
    vuepiniasessionstorage的坑默认的配置是开始localStorage如果用sessionstorage则发现数据存储不上,是因为缺少了序列化和反序列化import{parse,stringify}from'zipson'exportconstuseCounterStore=defineStore('counter',()=>{constcount=ref(0)......
  • Vue3 Pinia对state的订阅监听($subscribe,$onAction)数据监听
    <template><divclass="main-container":class="{'show-scroll':targetIsVisible}"><div:style="{height:frameHeight+'px'}"class="main-content":class="{'show-......
  • Vue中Pinia简介
    Pinia是一个进行vue状态管理的组件,他会创建一个带有state、actions、getters的option对象constuseCounterStore=defineStore('counter',{state:()=>({count:0}),getters:{double:(state)=>state.count*2},actions:{increment(){......
  • vuejs3.0 从入门到精通——Pinia——定义Store
    定义Store Store是用defineStore()定义的,它的第一个参数要求是一个独一无二的名字:import{defineStore}from'pinia'//你可以对`defineStore()`的返回值进行任意命名,但最好使用store的名字,同时以`use`开头且以`Store`结尾。(比如`useUserStore`,`useCartStore......
  • vuejs3.0 从入门到精通——Pinia——Store 是什么?
    Pinia——Store是什么?https://pinia.vuejs.org/zh/getting-started.html#what-is-a-store一、Store是什么? Store(如Pinia)是一个保存状态和业务逻辑的实体,它并不与你的组件树绑定。换句话说,它承载着全局状态。它有点像一个永远存在的组件,每个组件都可以读取和写入它。......
  • Vite4+Typescript+Vue3+Pinia 从零搭建(2) - tsconfig配置
    tsconfig配置项目代码同步至码云weiz-vue3-template关于tsconfig的配置字段可查看其他文档,如typeScripttsconfig配置详解tsconfig.json文件修改如下:{"compilerOptions":{"target":"ESNext",//将代码编译为最新版本的JS"useDefineForClassFields":tr......
  • Vite4+Typescript+Vue3+Pinia 从零搭建(1) - 项目初始化
    项目初始化项目代码同步至码云weiz-vue3-template前提准备1.node版本Node.js版本>=12,如果有老项目需要旧版本的,推荐用nvm管理node版本。PSC:\Users\Administrator>nvm--version1.1.11PSC:\Users\Administrator>nvmlist*16.20.2(Currentlyusing64-bit......
  • vue3中使用Pinia
    Pinia是一个用于Vue的状态管理库,类似Vuex,是Vue的另一种状态管理方案三大核心:state(存储的值),getters(计算属性),actions也可支持同步(改变值的方法,支持同步和异步)npminstallpinia@nextoryarnaddpinia@next模块化封装创建实例新建store/index.ts(src目录下新建store......
  • uniApp:使用vue3+Vite4+pinia+sass技术栈构建(03)-封装对象类
    1.在src文件夹创建models文件夹import{user}from"@/service/api"//用户信息返回的数据类型interfaceuserInfoType{username:string,phone:string}//返回类型interfaceResultType<T>{errno:number,errmsg:string,datas:T}classuser......
  • uniApp:使用vue3+Vite4+pinia+sass技术栈构建(02)-封装api请求
    前言在纯vue3开发的时候,使用axios进行api请求,但在uniapp中还需要安装axios的适配器uniapp-axios-adapter,否则小程序或者app请求不兼容。文档地址uniapp-axios-adapter-DCloud插件市场但在这里我们不使用axios,而是使用uniapp提供的请求方法uni.request进行封装。uni.request方......