pinia的使用

定义文件

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // could also be defined as
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

组件中的使用

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

export default {
  setup() {
    const counter = useCounterStore()

    counter.count++
    // with autocompletion ✨
    counter.$patch({ count: counter.count + 1 })
    // or using an action instead
    counter.increment()
  },
}

vue3安装

import { createPinia } from 'pinia'

app.use(createPinia())

vue2安装

import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // other options...
  // ...
  // note the same `pinia` instance can be used across multiple Vue apps on
  // the same page
  pinia,
})

与vuex对比的

优点

  1. ts的类型推断与类型提示会非常好。
  2. 兼容vue3的 composition-api写法。利于对hooks思想的架构升维。
  3. 更灵活的模块化导入。子模块之间也会变得更加灵活。
  4. store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或 MapAction 辅助函数,这在 Vuex 中很常见
  5. 开发人员是vue的核心成员。秉持着与vue一样的开发理念。

缺点

  1. devtools的开发工具兼容没有vuex那么友好。

You May Also Like

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注