vue3+Pinia的使用

Pinia官网地址

https://pinia.vuejs.org/

Pinia的优势

Pinia是一个全新的Vue状态管理库,是Vuex的代替者,尤雨溪强势推荐

  1. Vue2 和 Vue3 都能支持
  2. 抛弃传统的 Mutation ,只有 state, getter 和 action ,简化状态管理库
  3. 不需要嵌套模块,符合 Vue3 的 Composition api,让代码扁平化
  4. TypeScript支持
  5. 代码简洁,很好的代码自动分割

Pinia的基本使用

初始化项目

npm init vite@latest

安装

npm install pinia
yarn add pinia

挂载Pinia

// src/main.ts
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')

创建store

//  src/store/index.ts

import { defineStore } from "pinia";
export const mainStore = defineStore("main", {
  state: () => {
    return {
      msg: "hello world",
    };
  },
  getters: {},
  actions: {},
});

注:这是官网上提供的常规写法,我个人还是更偏向于下面这种写法:

//  src/store/index.ts

import { defineStore } from "pinia";

interface State {
  msg: string;
  count: number;
}

const defaultState:State = {
  msg: "hello world!"
}

export const mainStore = defineStore("main", {
  state: () => {
    return defaultState;
  },
  getters: {},
  actions: {},
  },
});

使用Store

//  src/components/HelloWorld.vue

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

<template>
  <h1>{
  
  {store.msg}}</h1>
</template>

<style scoped>

</style>

解构store

当store中的多个参数需要被使用到的时候,为了更简洁的使用这些变量,我们通常采用结构的方式一次性获取所有的变量名

  • ES传统方式解构(能获取到值,但是不具有响应性)
//  src/components/HelloWorld.vue

<script setup lang="ts">
import { mainSt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bigHead-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值