Vue3+TypeScript结合Pinia的使用

前言

伴随vue2到vue3的升级,官方已经用Pinia代替了Vuex成为官方的状态管理库。

一、Pinia是什么及特点?

1、Pinia是什么

在 vue 2.x 中,vuex 是官方的状态管理库,vue3官方强势推荐使用 pinia 作为状态管理库。

2、Pinia的特点

1、Pinia支持 vue2 和 vue3;
2、支持 vue3 中 setup 的写法,可以按照 setupComposition API 的方式返回状态和改变状态的方法,实现代码的扁平化;
3、支持 vuex 中 state、actions、getters 形式的写法,不再使用 mutations,开发时候不用根据同步异步来决定使用 mutations 或 actions,pinia 中只有 actions;
4、对 TypeScript 支持非常友好。

二、使用步骤

1.安装库

代码如下(示例):

yarn add pinia
# 或者使用 npm
npm install pinia

2.创建Pinia

1.1 main.ts文件

import { createApp } from 'vue'
import App from './App.vue'
import {setupStore} from './store/index'
const app = createApp(App)
setupStore(app)
app.mount('#app')

1.2 创建store文件夹下的index.ts

import type { App } from 'vue'
import { createPinia } from 'pinia'

const store = createPinia()

export const setupStore = (app: App<Element>) => {
  app.use(store)
}
export { store }

1.3 创建store文件夹下modules的文件夹,创建useAppStore.ts

import { defineStore  } from 'pinia'
interface AppState{
  count: number,
  list: Array<number>,
  name: string,
  age: number
}

export const useAppStore = defineStore('app', {
  state: ():AppState => {
    return {
      count: 0,
      list: [],
      name: '',
      age: 0
    }
  },
  actions: {
    addCount(step:number) {
      this.count+=step
    }
  },
  getters: {
    doubleCount(state) {
      return state.count*2
    }
  }
})

1.4 组件使用Pinia

<script setup lang="ts">
import { useAppStore } from './store/modules/useAppStore'
import { storeToRefs } from 'pinia'
const store = useAppStore()
// 转化响应式对象
const { count,doubleCount,list,name,age } = storeToRefs(store)
const { addCount } = store
const changeInfo = ()=>{
  //批量更新
	store.$patch(state=>{
		state.count++;
		state.list.push(1);
		state.name = 'qwe';
    state.age = 20
	})
}
</script>

<template>
<div>
  <button @click="addCount(10)">+1</button>
  <button @click="changeInfo">批量更新</button>
  <h2>count:{{count}}</h2>
  <h2>{{list}}</h2>
  <h2>{{name}}</h2>
  <h2>{{age}}</h2>
  <h2>doubleCount:{{doubleCount}}</h2>
</div>

</template>

<style scoped>
</style>

总结

以上仅仅简单介绍了Pinia在Vue3+Typescript中的使用,Pinia对于typescript的支持性更好,同时也简化了很多方法的写法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值