目录
Pinia是vue生态里Vuex的替代者,一个全新的vue状态管理库。
Pinia·是·Vue 的存储库,它允许您跨组件/页面共享状态
(让你可以在页面间实现数据的共享)
npm install pinia
package.json包中含有pinia

- import { createApp } from 'vue'
- import App from './App.vue'
- import {createPinia} from 'pinia'
- const app = createApp(App)
- app.use(createPinia())
- app.mount('#app')
在src目录下创建一个store包
store下建user.js
state是pinia的核心,是存储数据的地方,例如我们要存储一个user对象
- import {defineStore} from 'pinia'
- import {ref} from "vue";
- //第一种写法
- export default defineStore('first',()=>{
- const name=ref('name')
- const age=ref(12)
- return {name,age}
- })
- //第二种写法
- export default defineStore('user',{
- state:()=>{
- return {
- name:'name',
- age:12
- }
- }
- })
- <template>
- <a>{{userStore.name}}</a>
- <input type="text" v-model="userStore.name">
- </template>
-
- <script setup>
- import { toRef } from '@vue/reactivity'
- import user from '../store/user.js'//引入state
- const userStore = user()
-
-
- console.log(userStore.name)
- </script>
-
- <style>
-
- </style>

当我们更改表单中的数据时,前面的字符也会跟着改变,这种改变是通过更改状态库的数据而进行改变的
const {name,age} = StoreToRefs(userStore())
使用patch修改
- const handleClickPatch = () => {
- userStore.$patch((state)=>{
- userStore.name='小明'
- })
- }
先在store中写好action方法,再调用action
action中方法的创建
- actions: {
- changeState(){
- this.age++
- this.name = 'change helloPinia!!!'
- }
- }
action中方法的调用
- const handleClickActions = ()=>{
- userStore.changeState()
- }
计算属性,可以对state进行计算操作,它就是Store的计算属性,虽然在组件内也可以做计算属性,但是geetters可以在多组件之间复用,如果一个状态只在一个组件内使用是可以不用getters
例如
- import {defineStore} from 'pinia'
- import {ref} from "vue";
-
-
- export default defineStore('first',{state:()=>{
- const name=ref('name')
- const age=ref(12)
- return {name,age}
-
- },
- getters:{
- ageAdd(state){
- return this.age++
- }
- },
- action:{
-
- }
- })
这样,ageAdd可以直接通过store.ageAdd调用
例如
<a>{{userStore.ageAdd}}a>
在上面代码中我们一直只使用了一个Store仓库,在真实项目中我们往往是有多个Store的。有多个Stroe时,就会涉及Store内部的互相调用问题。
第一步:新建一个Store仓库
在\src\store下新建一个Hyy.ts文件:
- import { defineStore } from 'pinia'
-
- export const hyyStore = defineStore("hyyStore", {
- state:() => {
- return {
- list:["黄黄","小黄","黄小黄"]
- }
- },
- getters: {
- },
- actions: {
- }
- })
这是一个非常简单的仓库,只有state(状态数据),需要注意的是ID要是唯一的。有了这个仓库后,就可以回到index.ts这个仓库中调用了。
第二步:先引入Hyy这个store。
import { hyyStore } from './hyy'
第三步:然后在actions部分加一个getList( )方法。
这部分就写的很简单了,只是用console.log( )打印到控制台 上就可以了。
- actions: {
- changeState(){
- this.count++
- this.helloPinia = 'change helloPinia!!!'
- },
- getList(){
- console.log(hyyStore().list)
- }
- }
这样就实现了两个store中互相调用。