美文网首页
Pinia 简易使用

Pinia 简易使用

作者: 没名字的某某人 | 来源:发表于2023-01-08 16:13 被阅读0次

写在最前:本文转自掘金

关于Pinia

在vue3中,Pinia 替代了Vuex,简化了数据流修改,增加了插件的支持,成为了Vue3全家桶成员之一。

具体实例代码

创建 Pinia 实例

// index.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)  // 数据持久化

export default pinia

模块语法

其实有两种语法,分为

  • Option Stores 语法
  • Setup Stores 语法

先看第一种
传递带有 stategettersactions 属性的 Options 对象给 defineStore() 就可以定义一个 Store。

// counter.ts

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter' , {
  state: () => ({
    count: 0
  }),
  getters: {
    doubleCount: (state) => state.count*2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

这种语法与 Vuex 中定义 Store 的语法非常近似,但是少了 Mutation 字段。
不仅如此,这种写法也和 Vue2 的 Options API(选项式 API)结构类似:statedata 对应、getterscomputed 对应、actionsmethods 对应。
这种写法的好处就是结构非常清晰,容易上手。

再看第二种

// counter.ts

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

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

  return { count, doubleCount, increment }
})

在这种语法中,refstate 对应(使用 reactive 亦可)、computedgetters 对应、functionactions 对应。
这和 Vue3 新推出的 Composition API(组合式 API)非常类似!这样的话,在使用 Vue3 和 Pinia 的时候,就能统一语法了。

组件内使用

import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore ()
counterStore.increment()  //  更新数据
console.log(configStore.count)  // 获取数据

组件外使用

如果你准备在 Vue3 的 Setup 语法外引入 Pinia 的 Store,例如 useCounterStore。
直接 import { useCounterStore } from "@/store/xxxxxx" 是不行的,你得像这样:

import store from "@/store"

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

  return { count, doubleCount, increment }
})

/** 在 setup 外使用 */
export function useCounterStoreHook() {
  return useCounterStore(store)
}

然后引入 import { useCounterStoreHook } from "@/store/xxxxxx" 即可!

相关文章

网友评论

      本文标题:Pinia 简易使用

      本文链接:https://www.haomeiwen.com/subject/dtpucdtx.html