pinia有两种用法
第一种是函数的形式,另一种是对象的形式,下面简单说一下用法
首先在stores目录下创建ts或js文件,使用的前提是下载pinia
函数形式
首先导入defineStore,然后创建一个变量,也可以直接创建变量,一般都会在创建变量后会自动导入
import { defineStore } from 'pinia' //导入defineStore
//创建一个变量并进行导出
//函数形式,就是第二个参数是一个回调函数
export const useUserStore=defineStore('user',()=>{
//这里写要用到的数据
const count=ref(0)
const doubleCount=computed(()=>count.value*2)
function increment(){
count.value++
}
//需要的值要返回出来
return {count,doubleCount,increment }
})
使用的时候就在要用的组件的script中写创建变量的名字,例如useUserStore,需要导入这个,但是一般都会自动导入
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'
//useCounterStore()是定义的数据
useCounterStore().count=1
function add(){
useCounterStore().count *=2
}
</script>
<template>
<div>{{useCounterStore().count}}</div>
<div>{{useCounterStore().doubleCount}}</div>
<button @click="add">chenger</button>
<div>222</div>
</template>
对象形式
对象形式的就是第二个参数写成对象形式的,对应的写法也不同
import { defineStore } from 'pinia' //导入defineStore
//创建一个变量并进行导出
//对象形式,就是第二个参数是一个对象
export const userInfo=defineStore('u',{
//这里存放数据
state(){
return{
name='lalala'
}
},
//这里修改数据
action:{
setName(val){
this.name=val
}
}
})
使用方式
<script setup lang="ts">
import { userInfo} from '@/stores/counter'
//userInfo()是定义的数据
userInfo().count=1
//使用方法和函数式的相同
</script>
<template>
<div>{{userInfo().name}}</div>
</template>