状态管理

96 阅读1分钟

什么是状态管理?
它是一个独立的单元,由以下几个部分组成:

  • 状态:驱动整个应用的数据源;
  • 视图:对状态的一种声明式映射;
  • 交互:状态根据用户在视图中的输入而作出相应变更的可能方式

常见的Vue状态管理工具
VueX - vuex.vuejs.org/zh/
Pinia - pinia.vuejs.org/zh/

Pinia简介

安装

   npm i pinia         

main.js中引入

   import { createApp } from 'vue' 
   // 导⼊pinia
   import { createPinia } from 'pinia'
   import App from './App.vue'
   // 创建pinia实例 
   const pinia = createPinia() 
   const app = createApp(App) 
   // 使⽤pinia
   app.use(pinia) 
   app.mount('#app')

Store 是用 defineStore() 定义的,它的第一个参数要求是一个独一无二的名字:

     import { defineStore } from 'pinia'

    // 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
    // 第一个参数是你的应用中 Store 的唯一 ID。
    export const useAlertsStore = defineStore('alerts', {
      // 其他配置...
    })

Option Store

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

你可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。

Setup Store

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

  return { count, increment }
})

在set store中:

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