Vue3| Pinia 的语法

发布时间 2023-10-14 16:58:13作者: 嘎嘎鸭2

Pinia 是 Vue 的最新 状态管理工具,是 Vuex 的替代品

Pinia 的优势:

1. 提供更简单的 API(去掉了 mutation)

2. 提供符合 组合式风格的 API(和 Vue3 新语法统一)

3. 去掉了 modules 的概念,每一个 store 都是一个独立的模块

4. 配合 TypeScript 更加友好,提供可靠的类型推断

 

Pinia 基本语法:

定义 store:

import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名。这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools

// defineStore() 的第一个参数是你的应用中 Store 的唯一 ID。第二个参数可接受两类值:Setup 函数或 Option 对象

export  const  useAlertsStore = defineStore ( 'alerts' ,  {

      // 其他配置...

})

 

eg:

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
    const count = ref(0)

    return{
        count
    }
})
 

其他组件使用 Pinia:

<script setup>
import { useCounterStore } from '@/store/counter.js'
 
// 返回的是一个对象,所以 counterStore 是一个对象。counterStore.变量名或方法名  来使用。
const counterStore = useCounterStore() 

console.log(counterStore) 
</script>

<template>
<div>
  {{ counterStore.count }}   // 无论<script>还是<template>都是 counterStore.变量名或方法名
</div>
</template>
 
 

Setup Store

也存在另一种定义 store 的可用语法。与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。


export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

在 Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions