pinia简单入门小教程

258 阅读1分钟

一.安装

1.直接在安装脚手架时导入

image.png
2.控制台终端输入npm i pinia

二.在main.js中导入并注册

import {createPinia} from 'pinia'
const pinia = createPinia()
app.use(pinia)

三.定义模块

新建文件 src/store/counter.js,名字随意

// 先导入defineStore,使用这个API来创建仓库
import {defineStore} from 'pinia'
import {ref} from 'vue'

// defineStore的第一个参数是仓库名,即文件名,第二个参数是回调,需要在回调中定义数据和方法
export default defineStore('counter', () => {
    const count = ref(10)
    const addCount = () => {
        count.value++
    }
    
    // 一定要记得return,否则拿不到数据
    return {
        count,
        addCount
    }
})

四.使用模块

<script setup>
// 导入并获取store模块对象
import useCounterStore from '@/store/counter'
const counterStore = useCounterStore()
</script>

<template>
  <router-view></router-view>
  <!-- 调用store中的数据和方法 -->
  <div>{{counterStore.count}}</div>
  <button @click="counterStore.addCount">addCount</button>
</template>

计算属性/getters
在vue3中,getters直接无了,取而代之的就是computed

// 需要注意导入了computed
import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
export default defineStore('age', () => {
    const age = ref(17)
    const grow = () => {
        age.value++
    }
    
    // 直接在defineStore里使用computed,就相当于getters
    const tenYearsAgo = computed(() => age.value - 10)
    return {
        age,
        grow,
        tenYearsAgo
    }
})

你是否觉得xxxStore.写起来很麻烦?
可以使用storeToRefs这个api来解构xxxStore中的数据,同时保证数据还是响应式的
注意,这个api无法解构方法!

// 上面的代码可以解构
import {storeToRefs} from 'pinia'
const ageStore = useAgeStore()
// 注意,这里我结构了方法,并被下面的按钮调用,可以尝试发现,并不起效
const {age, grow} = storeToRefs(ageStore)


<div>{{age}}</div>
<button @click="grow">ageStore</button>

当你遇到异步数据或者其他情况无法用wacth获取到pinia中数据变动时,可以使用store.$subscribe监听store的变化,注意,这里的store换成你的状态仓库名,即

image.png