vue3+ts系列之pinia入门

1,812 阅读2分钟

一、安装pinia

npm i pinia
或
yarn add pinia

二、引入pinia

// main.ts
import { createApp } from 'vue'
import App from './App.vue'

// 引入pinia并实例化
import { createPinia } from 'pinia'
const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

三、创建pinia

// 1.在src目录下创建 store 文件
// 2.新增 counter.ts 测试仓库,代码如下

// counter.ts
import { defineStore } from "pinia";
import { computed, ref } from 'vue'
// defineStore 接受两个参数
//  参数1:仓库的id(字符串)
//  参数2:options(对象)
export const useCounterStore = defineStore('counter', () => {
    // 定义数据
    const counter = ref(100)
    
    // 定义计算属性
    const counterComputer = computed(() => {
        return counter.value * 2
    })
    
    // 定义方法
    const add = () => {
        counter.value++
    }
    return {
        counter,
        add,
        counterComputer
    }
})

四、在vue文件中使用

<template>
  <div>
    <h1>数量:{{ store.counter }}</h1>
    <h2>计算属性:{{ store.counterComputer }}</h2>
    <button @click="store.add">点我加加</button>
    <hr>
    <h1>数量:{{ counter }}</h1>
    <h2>计算属性:{{ counterComputer }}</h2>
    <button @click="add">点我加加</button>
  </div>
</template>

<script setup lang="ts">
import { useCounterStore } from './store/counter'
import { storeToRefs } from 'pinia';
// 普通用法
const store = useCounterStore()
// 解构用法
//  注意:方法可以直接解构使用,但ref、计算属性等直接解构使用,会失去响应式
//  若要解构ref、计算属性,需结合pinia提供的 storeToRefs 方法进行使用
const { add } = store
const { counter, counterComputer } = storeToRefs(store)

</script>

<style scoped>

</style>

五、pinia数据持久化

  1. 安装插件
npm i pinia-plugin-persistedstate
或
yarn add pinia-plugin-persistedstate
  1. 引入插件
// main.ts
import { createApp } from 'vue'
import App from './App.vue'

// 引入pinia
import { createPinia } from 'pinia'
// 引入持久化插件
import persist from 'pinia-plugin-persistedstate'
// 实例化pinia
const pinia = createPinia()

createApp(App)
    .use(pinia.use(persist)) // 注册插件
    .mount('#app')

3.在需要启用数据持久化的store文件中开启配置 persist:true

// counter.ts
import { defineStore } from "pinia";
import { computed, ref } from 'vue'
// defineStore第三个参数中启用持久化配置
//  当启用持久化后,pinia数据发生改变时,会自动将数据存到localStorage中
//  当页面刷新后,会自动读取localStorage
export const useCounterStore = defineStore('counter', () => {
    const counter = ref(100)

    const add = () => {
        counter.value++
    }
    const counterComputer = computed(() => {
        return counter.value * 2
    })
    return {
        counter,
        add,
        counterComputer
    }
}, {
    persist: true // 开启pinia数据持久化
})

六、总结

  1. pinia中定义的数据(如ref)可以类比为vuex中的state;
  2. pinia中定义的计算属性可以类比为vuex中的getters;
  3. pinia中定义的方法可以类比为vuex中的mutations、actions,区别在于pinia中没有区分同步和异步;
  4. pinia中没有模块化的概念,每个ts文件都为一个全局仓库,不同于vuex仅有一个仓库;
  5. 相对于vuex的各种繁琐的api,pinia用法更简便