pinia核心概念
Pinia从使用角度和之前的Vuex一样 Pinia更友好的TypeScipt支持。
Store是保存状态与业务逻辑的实体,有三个核心概念。
可以理解为 data、computed、methods
◆ state:存储全局状态
◆ getters:类似于组件的computed,根据已有state做数据拼接加工,也具有缓存的特性
◆ actions:类似于组件的methods,用来封装业务逻辑,支持同步和异步
使用Pinia
- 安装Pinia
yarn add pinia
npm install pinia
-
创建pinia文件
store文件里index.js
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
- main.js导入并引用
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './stores'
createApp(App).use(pinia).mount('#app')
- store下的counter文件内容
import { defineStore } from 'pinia'
// 定义关于counter的store
// defineStore 是返回一个函数 函数命名最好有use前缀,根据函数来进行下一步操作
const useCounter = defineStore('counter',{
state: () => {
count:1
},
// 类似 computed 主要做数据加工缓存
getters:{
doubleCounter(){
return this.count * 2
},
actions:{
add(){
this.count++
},
//传参
update(num){
this.count += num
}
}
}
})
在页面中使用 counter 定义的属性
<template>
<div class="home">
<h2>Home View</h2>
<h2>count: {{ counterStore.count }}</h2>
<button @click="incrementCount">count+1</button>
</div>
</template>
<script setup>
import useCounter from '@/stores/counter';
const counterStore = useCounter()
</script>
可以解构 state 直接调用
const { count } = useCounter()
但会失去响应式,需要 toRef 或者 pinia 自带 storeToRefs 包一层让它有响应式
import { toRefs } from 'vue'
import { storeToRefs } from 'pinia'
const counterStore = useCounter()
const { count } = toRefs(counterStore)
or
const { count } = storeToRefs(counterStore)
在页面中点击按钮修改store里面的count 值
方法一
const incrementCount = ()=> {
counterStore.count++
}
方法二 $patch 它允许同时多个修改
const incrementCount = ()=> {
counterStore.$patch({
counter:count,
name:'kobe'
})
}
访问store里面的getters 定义的函数
和state 一样的访问方式
const counterSotre = useCounter()
console.log(counterStore.doublCounter)
Actions 使用
const incrementCount = ()=> {
counterStore.add()
counterStore.update(10)
}
支持异步
actions:{
async fetchHome(){
//???请求
const res = await fetch('?????')
const data = await res.json()
console.log('data',data)
return data
}
}
vue页面
const counterSotre = useCounter()
counterStore.fetchHome().then(res => {
console.log(res)
})
重置State:
可以调用store上的$reset()方法将状态重置到其初始值
const counterStore = useCounter()
conterStore.$reset()
替换State
conterStore.$state = {
counter:1,
name:'why'
}