Vue3 小兔鲜:Pinia入门

news/2024/10/17 4:51:26/

Vue3 小兔鲜:Pinia入门

Date: May 11, 2023
Sum: Pinia概念、实现counter、getters、异步action、storeToRefs保持响应式解构


什么是Pinia

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

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

中文文档:https://pinia.vuejs.org/zh




创建空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}
})

理解:

在定义store的时候,我们采取和组合式api一样的写法,不过需要return回需要的数据与方法。

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>

案例:

counter.js

// 导入一个方法 defineStore
import { defineStore } from 'pinia'
import { ref } from 'vue'export const useCounterStore =  defineStore('counter' , () => {// 定义数据(state)const count = ref(0)// 定义修改数据的方法(action 同步+异步)const increment = () => {count.value++}// 以对象的方式return供组件使用return {count,increment}
})

App.vue

<template><button @click="counterStore.increment">{{ counterStore.count }}</button>
</template><script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore);
</script><style></style>

效果:实现一个计数器




实现getters

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

实现:这里的doubleCount永远会随着count的变化而变化

// 数据(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>

理解:数据和方法如何解构赋值

数据解构赋值:

采用解构赋值,并采用方法包裹

方法解构赋值:

直接解构赋值即可

App.vue

<template><button @click="increment">{{ count }}</button><p>{{ doubleCount }}</p><ul><li v-for="item in counterStore.getList" :key="item.id">{{ item.name }}</li></ul>
</template><script setup>// 1. 导入 use 打头的方法import { useCounterStore } from '@/stores/counter'import { onMounted } from 'vue'import { storeToRefs } from 'pinia'// 2. 执行方法得到store实例对象const counterStore = useCounterStore()// 数据解构:// 直接解构赋值(会造成响应式丢失)// 这里采用方法包裹(可以保持响应式的更新)const { count, doubleCount } = storeToRefs(counterStore)// 方法解构:// 注: 方法解构直接从counterStore中解构赋值即可const { increment } = counterStoreonMounted(() => {counterStore.getList()})
</script>

效果:

Untitled

注意:

如图所示,直接解构赋值,则只会传值回来。而采用解构赋值,并采用方法包裹,则传回对象。

总结:

  1. pinia是用来做什么的?

    集中状态管理工具,新一代的vuex

  2. Pinia中还需要mutation吗?

    不需要,action既支持同步也支持异步
    Pinia如何实现getter?
    computed计算属性函数

  3. Pinia产生的Store如何解构赋值数据保持响应式?

storeToRefs


http://www.ppmy.cn/news/126511.html

相关文章

TA100 L1.2.1

小姐姐的作业&#xff0c;我用的是unity2020,shadergraph里没有mainlight节点&#xff0c;所以上网找了一个shader嫖了里面的mainlight节点&#xff0c;不知道效果正不正确&#xff08;但这样就连不上position&#xff09;

LC001

1.两数之和&#xff1a;‘ class Solution:def twoSum( nums, target):for i in nums:if target - i in nums:if i ! target - i:return [nums.index(i), nums.index(target - i)]elif nums.count(i) > 1:index1 nums.index(i)nums.remove(i)return [index1, nums.index(i…

AT680A 超级电容漏电流测试仪 技术参数

AT680A 是采用高性能微处理器控制的超级电容漏电流测试仪。数控测试电压&#xff1a;1.000V~10.000V&#xff0c;充电电流2A&#xff0c;4量程测试&#xff0c;使漏电流准确度提高到1%&#xff0c;它可以测试0.001μA~200mA的电流&#xff0c;显示位数9999数。测试速度可达55次…

L1-006

L1-006 连续因子 (20分) 一个正整数 N 的因子中可能存在若干连续的数字。例如 630 可以分解为 3567&#xff0c;其中 5、6、7 就是 3 个连续的数字。给定任一正整数 N&#xff0c;要求编写程序求出最长连续因子的个数&#xff0c;并输出最小的连续因子序列。输入格式&#xff1…

Telerik 2020 R1 SP1 All Components -完整更新版

Telerik 专注于微软.Net平台的表示层与内容管理控件&#xff0c;提供高度稳定性和丰富性能的组件产品DevCraft&#xff0c;并可应用在非常严格的环境中。Telerik拥有 Microsoft, HP, Alcoa, BP, Harper Collins, Siemens, T-Mobile, HJ Heinz和一些最主要的教育机构和很多政府机…

B1001

害死人不偿命的(3n1)猜想 (15分) n%2&#xff01;0代表是奇数&#xff0c;if的判断条件里&#xff01;0可省略。 代码&#xff1a; #include<cstdio>int main() {int count 0, n;scanf("%d", &n);while(n!1){if(n%2) n (3*n1)/2;else n / 2;count;}p…

2.1 rvos简介

rvos简介 1 简介课程地址源码地址课程交流群 1 简介 rvos&#xff08;RISC-V OS&#xff09;是基于riscv开发的一个简单的适合入门的实时操作内核。 其作者是汪辰老师&#xff0c;有对应的源码及视频。 汪辰老师的这么课程讲的非常好&#xff0c;强烈推荐大家去观看 课程地址…