vue3中的pinia的使用

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; //方法的引入

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值