likes
comments
collection
share

pinia的基础使用

作者站长头像
站长
· 阅读数 14

概念

  • pinia核心概念

    • state: 状态

    • actions: 修改状态(包括同步和异步,pinia中没有mutations)

    • getters: 计算属性

  • 为什么使用pinia

    • piniavuex4一样,也是vue官方的状态管理工具
    • pinia相比vuex4,对于vue3的兼容性更好
    • pinia相比vuex4,具备完善的类型推荐
    • piniaAPI 设计非常接近 Vuex 5 的提案

安装

yarn add pinia

npm i pinia

挂载

  • main.js文件中挂载pinia
import { createApp } from 'vue';
import App from './App.vue';
//引入pinia
import { createPinia } from "pinia";

const app = createApp(App);
//注册
const pinia = createPinia()
//使用
app.use(pinia)
app.mount('#app');

新建文件

  • src/store文件夹中创建index.js文件

  • state 相当于 data

  • actions 相当于 methods

  • getters 相当于 computed

import { defineStore } from 'pinia'
// 创建store,命名规则: useXxxxStore
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
   
  },
  actions: {
    
  },
})
//导出pinia
export default useCounterStore

使用

  • 在组件中使用pinia
<script setup>
// 引入
import useCounterStore from './store/counter'
//使用
const counter = useCounterStore()
</script>

<template>
  <h1>根组件---{{ counter.count }}</h1>
</template>

<style></style>

actions

  • 不管是同步还是异步的代码,都可以在actions中完成
import { defineStore } from 'pinia'
// 1. 创建store
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})

export default useCounterStore
  • 在组件中使用
<script setup>
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <h1>根组件---{{ counter.count }}</h1>
  <button @click="counter.increment">加1</button>
  <button @click="counter.incrementAsync">异步加1</button>
</template>

getters

  • pinia中的getters和vuex中的基本是一样的,也带有缓存的功能

  • 在getters中提供计算属性

import { defineStore } from 'pinia'
// 1. 创建store
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    double() {
      return this.count * 2
    },
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})

export default useCounterStore

  • 在组件中使用
  <h1>根组件---{{ counter.count }}</h1>
  <h3>{{ counter.double }}</h3>