包教包会vue3+ts状态管理工具pinia

  • Post author:
  • Post category:vue


一、Pinia介绍

定义:pinia是和vuex一样的状态管理工具

语法:和

Vue3

一样,它实现状态管理有两种语法:选项式API 和 组合式API

支持:vue2、typeScript、devtools

二、使用步骤

1.安装

pnpm add pinia

yarn add pinia

npm i pinia

2.在main.ts中导入,实例化

// 导入pinia
import { createPinia } from 'pinia'
const pinia = createPinia()

// 挂载pinia
createApp(App).use(pinia).mount('#app')

3.创建pinia仓库并使用


(1)组合式API写法

创建:

import { defineStore } from 'pinia'
// import * as obj from 'pinia'  
// console.log(obj);   
import { ref } from 'vue'
/* 1.组合式pinia */
export const userStoreHr = defineStore('hr', () => {
  // (1)模拟state
  let num = ref(100)
  const arr = ref([1, 2, 3, 4, 5])
  // (2)模拟mutation
  const changeNum = () => {
    num.value += 100
  }
  // (3)模拟action
  const activeArr = () => {
    setTimeout(() => {
      const n = Math.floor(Math.random() * 10) + 1
      arr.value.push(n)
    }, 1000)
  }
  // (4)模拟getters
  const total = () => {
    return arr.value.reduce((sum, item) => item + sum, 0)
  }

  return { num, changeNum, activeArr, total }
})

export default userStoreHr

使用:

<script setup lang="ts">
import { userStoreHr } from './store/hr'
const store = userStoreHr()
// console.log(store);
</script>

<template>
  <div>
    <div>app.vue</div>
    <div>num:{{ store.num }} total:{{ store.total() }}</div>
    <button @click="store.changeNum()">按钮1</button>
    <button @click="store.activeArr()">按钮2</button>
</div>
</template>


(2)选项式API写法

创建:

// 创建pinia仓库
import { defineStore } from "pinia";

export const useStoreTt = defineStore('tt', {
  state: () => {
    return {
      count: 10,
      price: 50
    }
  },
  actions: {
    addPrice() {
      this.price += 1
      console.log(this, '组合式API可以用this');
    }
  },
  getters: {
    /* 以下两种写法都可以 */

    // total(): number {
    //   return this.count * this.price
    // }  

    total: (state) => {
      return state.count * state.price
    }
  },
})

export default useStoreTt

使用:

<script setup lang="ts">
import { useStoreTt } from './store/tt'
const store = useStoreTt()

</script>

<template>
  <div>
    <div>app.vue</div>
    <div>count :{{ store.count }} price : {{ store.price }}</div>
    <div>total :{{ store.total }}</div>
    <button @click="store.addPrice()">addPrice</button>
</div>
</template>


(3)storeToRefs的使用

解决:解构数据后,响应式失效的问题(不能解构函数)

<script setup lang="ts">
import { useStoreTt } from './store/tt'
// 导入storeToRefs 
import { storeToRefs } from 'pinia';
const store = useStoreTt()
// 解构的时候调用storeToRefs 
const { count, price } = storeToRefs(store)

</script>

<template>
  <div>
    <div>app.vue</div>
    <!-- 模板中直接使用 -->
    <div>count :{{ count }} price : {{ price }}</div>
    <div>total :{{ store.total }}</div>
    <button @click="store.addPrice()">addPrice</button>
</div>
</template>



版权声明:本文为weixin_48082900原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。