【vue3】基础知识点-pinia

学习vue3,都会从基础知识点学起。了解setup函数,ref,recative,watch、computed、pinia等如何使用

今天说vue3组合式api,pinia

戳这里,跳转pinia中文文档

官网的基础示例中提供了三种写法
1、选择式api,类似于vuex的写法
在这里插入图片描述
2、组合式api,vue3 组合式api写法
在这里插入图片描述
3、借助辅助函数mapStores()、mapState() 或 mapActions()
在这里插入图片描述

本文主要讲第二种写法,它与vue3的语法风格是统一的

使用:
1、定义store(state+action+getters)
//defineStore函数创建store实例对象
//defineStore函数需要传递两个参数,第一个参数:小仓库名字(唯一id,不可重复,
用于区分是哪个store,这样就不会出现命名冲突,组件中使用仓库数据是通过定义变量(useCounterStore )接收defineStore方法返回的函数,和仓库名(counter)没有直接关系)
//第二个参数:小仓库配置对象
//defineStore方法执行会返回一个函数,函数作用就是让组件可以获取到仓库数据

import {
    
    defineStore} from 'pinia'
import {
    
    ref} from 'vue'
import axios from 'axios'

export const useCounterStore = defineStore('counter',()=>{
    
    
//数据(state)
const count = ref(0)
const API_URL = '/api/booklist'
cosnt list = ref([])

//getter
const deoubleCount = computed(()=>count.value*2)

//修改数据的方法
//(同步action)
const increment= ()=>{
    
    
count.value++
}
//(异步action,与组件中定义数据和方法的风格完全一致)
const loadList = async ()=>{
    
    
const res = await axios.get(API_URL)
list.value = res.data 
}
//以对象形式返回
return {
    
    count,increment,deoubleCount,list,loadList  }
})

2、组件使用store

<script setup>
//1、导入`useCounterStore `方法
import {
    
    useCounterStore } from '@/stores/counter'

//2、执行方法得到counterStore对象
const counterStore = useCounterStore ()

console.log(counterStore)

//counterStore 对象包含的就是counter仓库中return出来的对象

onMounted(()=>{
    
    
counterStore.loadList()  
})

</script>

<template>

<button @click="counterStore.increment ">

{
    
    {
    
    counterStore.count}}{
    
    {
    
    counterStore.deoubleCount }}

</button>

<ul>
<li v-for="item in counterStore.list" :key="item.id")>
{
    
    {
    
    item.name}}
</li>
</ul>

</template>

打印counterStore
在这里插入图片描述

storeToRefs

为什么要使用storeToRefs,可以简化写法,原先的counterStore.count通过解构可以直接使用count。中文文档中特意注明,不能直接对store进行解构,会破坏响应式。响应式丢失,视图也不再更新。所以使用storeToRefs函数可以辅助保持数据(state+getter)的响应式解构

在这里插入图片描述
有效写法:
在这里插入图片描述

在这里插入图片描述
观察下区别,错误写法下,打印count,deoubleCount ,拿到的是两个0

在这里插入图片描述

正确写法下,,打印count,deoubleCount ,拿到的是两个响应式的对象
在这里插入图片描述
方法不需要通过storeToRefs函数解构赋值,直接从原来的counterStore中解构赋值

const {
    
    increment } = counterStore

猜你喜欢

转载自blog.csdn.net/weixin_49668076/article/details/132182309