Vue3新的状态管理库-Pinia(保姆级别教程)

目录

1.什么是Pinia

Pinia是Vue的专属的最新状态管理库, 是Vuex状态管理工具的替代品

vue.js官网 https://cn.vuejs.org/guide/introduction.html

Pina网址:https://pinia.vuejs.org/zh/

2.为什么使用Pinia

  • 2.1.提供了更加简单的API(去掉了mutation)

  • 2.2.提供了符合组合式风格的API(和Vue3新语法统一)

  • 2.3.去掉了modules的概念, 每一个store都是独立的模块

  • 2.4.搭配TypeScript一起使用提供可靠的类型推断

3.创建项目

javascript 复制代码
npm init vue@latest
javascript 复制代码
 cd vue3-vite-pinia
 npm install
 npm run dev

4.检查Pinia的安装版本

复制代码
打开package是否安装上Pinia

```javascript
  "dependencies": {
    "pinia": "^2.1.6",
    "vue": "^3.3.4",
    "vue-router": "^4.2.4"
  },

5.main.js引入Pinia

javascript 复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

6.定义Store-组合式API写法(推荐)

与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。

javascript 复制代码
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import axios from 'axios'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  // 实现getter
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

// 获取接口返回的数组
// const arrList = ref([])
// const getList = async()=>{
//   const res = await axios.get(BASE_URL)
//   if(res.state == 'ok'){
//     arrList.value = res.data
//   }
// }

  return { count, doubleCount, increment }
})

7.getters的实现

Pinia中的getters直接使用computed函数进行模拟

8.action的异步实现

action中实现异步和组件中定义数据和方法的风格完全一致

安装axios

javascript 复制代码
npm install axios

查看axios

编写action函数

javascript 复制代码
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import axios from 'axios'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  // 实现getter
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

// 获取接口返回的数组
const arrList = ref([])
const getList = async()=>{
  const res = await axios.get(BASE_URL)
  if(res.state == 'ok'){
    arrList.value = res.data
  }
}

  return { count, doubleCount, increment }
})

9.storeToRefs

显而易见这样的写法会导致响应式的丢失

那么我们使用storeToRefs函数可以腐竹保持数据(state+getter)的响应式解构

相关推荐
哆啦A梦158814 分钟前
62 对接支付宝沙箱
前端·javascript·vue.js·node.js
用户841794814561 小时前
vxe-table 使用 spanMethod 合并卡顿的解决方案
vue.js
临江仙4551 小时前
Vite 性能优化实战:从 0 到 1 打造极速开发体验(附完整配置)
vue.js·vite
q_19132846952 小时前
基于Springboot2+Vue2的旅游景点购票系统
java·vue.js·spring boot·后端·mysql·毕业设计·计算机毕业设计
季禮祥2 小时前
彻底弄懂KeepAlive
javascript·vue.js·面试
小胖霞2 小时前
彻底搞懂 JWT 登录认证与路由守卫(五)
前端·vue.js·node.js
灵魂学者2 小时前
Vue3.x —— ref 的使用
前端·javascript·vue.js
一 乐2 小时前
鲜花销售|基于springboot+vue的鲜花销售系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
梦6502 小时前
VUE树形菜单组件如何实现展开/收起、全选/取消功能
前端·javascript·vue.js
天天向上10243 小时前
Vue 配置一次打包执行多个命令,并将分别输出到不同的文件夹
前端·javascript·vue.js