Pinia 是 Vue 3 的官方推荐状态(数据)管理库,提供了一种简单、直观且组件友好的方式来管理应用状态(数据,函数)
1.安装依赖:
npm i pinia
2.注册pinia
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from "pinia"
const app =createApp(App)
const pinia=createPinia()
app.use(pinia)
app.mount('#app')
3.创建pinia(在store文件夹中)
介绍:store
是一个保存:状态、业务逻辑 的实体,每个组件都可以读取、写入它。
模版:
import {ref} from "vue"
import {defineStore} from "pinia"
export const use文件名Store = defineStore("文件名",()=>{
return {}
})
实例:
//如下:
import {ref}from "vue"
import {defineStore}from "pinia"
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
4.使用pinia中的数据:
组件的script里
模版:
import {use文件名Store} from "@/store/文件名"
const 文件名Store =use文件名Store
实例:
import {useCounterStore} from "@/stores/counter"
console.log(useCounterStore)
const counterStore=useCounterStore()
const{count} = counterStore
storeTorefs
借助storeToRefs将store中的数据转为ref对象,方便在模板中使用。
注意:pinia提供的storeToRefs只会将数据做转换(对方法没有) ,而Vue的toRefs会转换store中数据和方法。
<template>
<div class="count">
<h2>当前求和为:{
{sum}}</h2>
</div>
</template>
<script setup lang="ts" name="Count">
import { useCountStore } from '@/store/count'
/* 引入storeToRefs */
import { storeToRefs } from 'pinia'
/* 得到countStore */
const countStore = useCountStore()
/* 使用storeToRefs转换countStore,随后解构 */
const {sum} = storeToRefs(countStore)
</script>
介绍:
storeToRefs
是 Pinia 提供的一个辅助函数,用于将 Pinia store 中的状态(state)和响应式属性转换成一组解构的响应式引用,便于在 Vue 组件中使用。而 Vue 的 toRefs
函数则是用来将对象转换成解构的响应式引用。Pinia 的 storeToRefs
仅转换 store 中的数据属性,不包括方法(如 actions 或 computed properties),意味着使用 storeToRefs
后,你将获得一个包含解构的响应式引用的对象,这些引用指向原始 store 中的状态和响应式属性,但不包括 actions(方法)。
import {useCounterStore} from "@/stores/counter"
console.log(useCounterStore)
const counterStore=useCounterStore()
const{count} = counterStore
const increment = counterStore.increment; //方法的引入