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)的响应式解构

相关推荐
咪库咪库咪9 小时前
vue3-组件
vue.js
10share9 小时前
100行代码 模拟实现Vue 响应式系统
前端·vue.js
用户40993225021212 小时前
Vue状态管理入门第四章:组合式store和SSR风险
前端·vue.js·后端
锋行天下1 天前
半秒开!还有谁!!!
前端·vue.js·架构
JING小白1 天前
Day 1 重学Vue:响应式系统的“底层逻辑”变更,Vue2旧时代的终结与Vue3新时代的开启
前端·vue.js
OpenTiny社区1 天前
从零开发 AI 聊天页要两周?试试这款 Vue3 垂直对话组件库 TinyRobot,直接开箱即用
前端·vue.js·github
Cobyte1 天前
22.Vue Vapor 组件 props 的实现
前端·javascript·vue.js
白雾茫茫丶2 天前
探索 Nuxt.js 全栈能力:用 Better-Auth 打造类型安全的 RBAC 权限系统
前端·vue.js·nuxt.js
向阳而生6602 天前
文件上传也能玩出花?Vue3 教你优雅实现“选择文件”和“选择文件夹”🚀
vue.js
3630458412 天前
Signal 带来的架构问题思考
前端·vue.js