当前位置: 首页 > news >正文

【pinia】Pinia入门和基本使用:

文章目录

    • 一、 什么是pinia
    • 二、 创建空Vue项目并安装Pinia
      • 1. 创建空Vue项目
      • 2. 安装Pinia并注册
    • 三、 实现counter
    • 四、 实现getters
    • 五、 异步action
    • 六、 storeToRefs保持响应式解构
    • 七、基本使用:
            • 【1】main.js
            • 【2】store=》index.js
            • 【3】member.ts


一、 什么是pinia

Pinia 是 Vue 的专属状态管理库,可以实现跨组件或页面共享状态,是 vuex 状态管理工具的替代品,和 Vuex相比,具备以下优势

  1. 提供更加简单的API (去掉了 mutation )
  2. 提供符合组合式API风格的API (和 Vue3 新语法统一)
  3. 去掉了modules的概念,每一个store都是一个独立的模块
  4. 搭配 TypeScript 一起使用提供可靠的类型推断

二、 创建空Vue项目并安装Pinia

1. 创建空Vue项目

npm init vue@latest

2. 安装Pinia并注册

npm i pinia
import { createPinia } from 'pinia'const app = createApp(App)
// 以插件的形式注册
app.use(createPinia())
app.use(router)
app.mount('#app')

三、 实现counter

核心步骤:

  1. 定义store
  2. 组件使用store

1- 定义store

import { defineStore } from 'pinia'
import { ref } from 'vue'export const useCounterStore = defineStore('counter', ()=>{// 数据 (state)const count = ref(0)// 修改数据的方法 (action)const increment = ()=>{count.value++}// 以对象形式返回return {count,increment}
})

2- 组件使用store

<script setup>// 1. 导入use方法import { useCounterStore } from '@/stores/counter'// 2. 执行方法得到store store里有数据和方法const counterStore = useCounterStore()
</script><template><button @click="counterStore.increment">{{ counterStore.count }}</button>
</template>

四、 实现getters

getters直接使用计算属性即可实现

// 数据(state)
const count = ref(0)
// getter (computed)
const doubleCount = computed(() => count.value * 2)

五、 异步action

思想:action函数既支持同步也支持异步,和在组件中发送网络请求写法保持一致
步骤:

  1. store中定义action
  2. 组件中触发action

1- store中定义action

const API_URL = 'http://geek.itheima.net/v1_0/channels'export const useCounterStore = defineStore('counter', ()=>{// 数据const list = ref([])// 异步actionconst loadList = async ()=>{const res = await axios.get(API_URL)list.value = res.data.data.channels}return {list,loadList}
})

2- 组件中调用action

<script setup>import { useCounterStore } from '@/stores/counter'const counterStore = useCounterStore()// 调用异步actioncounterStore.loadList()
</script><template><ul><li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li></ul>
</template>

六、 storeToRefs保持响应式解构

直接基于store进行解构赋值,响应式数据(state和getter)会丢失响应式特性,使用storeToRefs辅助保持响应式

<script setup>import { storeToRefs } from 'pinia'import { useCounterStore } from '@/stores/counter'const counterStore = useCounterStore()// 使用它storeToRefs包裹之后解构保持响应式const { count } = storeToRefs(counterStore)const { increment } = counterStore</script><template><button @click="increment">{{ count }}</button>
</template>

七、基本使用:

【1】main.js
import { createSSRApp } from 'vue'
import App from './App.vue'// 导入 pinia 实例
import pinia from './stores'
import persist from 'pinia-plugin-persistedstate'
// 使用持久化存储插件
pinia.use(persist)export function createApp() {// 创建 vue 实例const app = createSSRApp(App)// 使用 piniaapp.use(pinia)return {app,}
}

在这里插入图片描述

【2】store=》index.js
import { createPinia } from 'pinia'// 创建 pinia 实例
const pinia = createPinia()// 默认导出,给 main.ts 使用
export default pinia

在这里插入图片描述

【3】member.ts
import type { LoginResult } from '@/types/member'
import { defineStore } from 'pinia'
import { ref } from 'vue'// 定义 Store
export const useMemberStore = defineStore('member',() => {// 会员信息const profile = ref<LoginResult>()// 保存会员信息,登录时使用const setProfile = (val: LoginResult) => {profile.value = val}// 清理会员信息,退出时使用const clearProfile = () => {profile.value = undefined}// 记得 returnreturn {profile,setProfile,clearProfile,}},{// 网页端配置// persist: true,// 小程序端配置persist: {storage: {getItem(key) {return uni.getStorageSync(key)},setItem(key, value) {uni.setStorageSync(key, value)},},},},
)

在这里插入图片描述

http://www.lryc.cn/news/117966.html

相关文章:

  • Linux 文件系统(一)系统目录
  • 『CV学习笔记』Opencv和PIL Image以及base64编码互相转化
  • 行业追踪,2023-08-07
  • CSRF 攻击和 XSS 攻击分别代表什么?如何防范?
  • RabbitMQ: 详解、使用教程和示例
  • redis NOAUTH Authentication required 可能不是密码问题
  • 动态规划解0-1背包问题(超详细理解)
  • 有哪些可能引起前端安全的问题?
  • 【Unity实战100例】用户头像圆形遮罩使用Shader不用Mask组件
  • arm-linux-gnueabihf-g++ gcc编译、优化命令 汇总
  • vmwera中安装的centos8出现ifconfig不可用
  • 线性表中的时间复杂度
  • ensp与虚拟机搭建测试环境
  • linux内核中的 指针 和 unsigned long
  • STM32--GPIO
  • 剑指 Offer ! 61. 扑克牌中的顺子
  • 《玩转Python数据分析专栏》大纲
  • Zabbix自动注册服务器及部署代理服务器
  • SpringBoot下使用自定义监听事件
  • 并发编程面试题1
  • 【对于一维信号的匹配】对一个一维(时间)信号y使用自定义基B执行匹配追踪(MP)研究(Matlab代码实现)
  • 【Oracle 数据库 SQL 语句 】积累1
  • Django中级指南:理解并实现Django的模型和数据库迁移
  • Chatgpt API调用报错:openai.error.RateLimitError
  • 一键获取数百张免费商用人脸!AI人脸生成器来袭
  • 跳跃游戏 II——力扣45
  • Stable Diffusion - 常用的负向提示 Embeddings 解析与 坐姿 (Sitting) 提示词
  • 工厂方法模式(一):C#实现指南
  • Spring接口InitializingBean的作用和使用介绍
  • Excel---成绩相同者,名次并列排列,三步搞定