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

相关推荐
Momo__5 小时前
Vue 3.6 Vapor Mode:跳过虚拟 DOM,性能极致优化
前端·vue.js
walking9576 小时前
重新学习前端之JavaScript
前端·vue.js·面试
walking9576 小时前
重新学习前端之HTML
前端·vue.js·面试
walking9576 小时前
重新学习前端之Vue
前端·vue.js·面试
泉城老铁6 小时前
springboot实现word转换pdf
vue.js·后端
walking9576 小时前
重新学习前端之Linux
前端·vue.js·面试
walking9576 小时前
重新学习前端之CSS
前端·vue.js·面试
walking9576 小时前
重新学习前端之Git
前端·vue.js·面试
Hello--_--World7 小时前
Vue指令:v-if vs v-show、v-if 与 v-for 的优先级冲突、自定义指令
前端·javascript·vue.js
Hello--_--World10 小时前
Vue:虚拟Dom
前端·javascript·vue.js