pinia使用记录

89 阅读1分钟

vue2使用vuex3,vue3使用vuex4,未来会使用pinia替代vuex。

vuex有state getters mutations actions modules

pinia有state getters actions

开始使用

安装

npm i pinia
yarn add pinia

在main.js中注册

//main.js
import { createPinia } from 'pinia' 
app.use(createPinia())

定义一个store(store/xxx.js)

options store

state定义参数相当于datagetters相当于computedactions可同时写同步异步方法。

import { defineStore } from 'pinia'
// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,
同时以 `use` 开头且以 `Store` 结尾。
(比如 `useUserStore``useCartStore``useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

setup store

将第二个参数从options对象改成function箭头函数,ref相当于statecomputed()相当于gettersfunction相当于actions

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

  return { count, increment }
})

使用store

<script setup>
import { useCounterStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
</script>

注意:store解构需要使用storeToRef()进行包裹

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>

store的一些实例方法

重置$reset

const store = useStore()
store.$reset()

变更$patch

全部变更(接受一个对象)
store.$patch({
  count: store.count + 1,
  age: 120,
  name: 'DIO',
})
按需变更(接受一个函数,参数为state)
store.$patch((state) => {
  state.items.push({ name: 'shoes', quantity: 1 })
  state.hasChanged = true
})