Vue3Pinia入门学习

什么是pinia

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

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

创建空Vue项目并安装Pinia

参考pinia官方文档https://pinia.vuejs.org/zh/getting-started.html
image.png

1. 创建空Vue项目

npm init vue@latest

2. 安装Pinia并注册、

npm i pinia

在main.js中

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'

//导入createPinia
import { createPinia } from 'pinia'

//执行方法得到实例
const pinia = createPinia()

//把实例挂载到app应用上

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

基础用法:

实现counter

核心步骤:

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

1- 定义store
创建包stores
image.png

//导入一个方法 definStore

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
    }

})

2- 组件使用store

<script setup>
//导入use打头的方法

import {useCounterStore} from '@/stores/counter'

//执行方法得到store实例对象
const counterStore=useCounterStore()
console.log(counterStore)
</script>


<template>
  <button @click="counterStore.increment">{{counterStore.count}}</button>
  
</template>


<style>

</style>

实现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([])
  // 异步action
  const 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()
  // 调用异步action
  counterStore.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>

方法可以直接解构赋值
image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值