Skip to content

pinia技术

📖 pinia是什么?

Pinia 是 Vue 的状态管理库,它的核心作用是集中管理和共享 Vue 应用中跨组件的、需要全局访问的数据。

  • 任何组件(无论层级深浅)都可以去这个仓库里读取数据。
  • 任何组件都可以去这个仓库里修改数据。
  • 一旦数据被修改,所有正在使用该数据的组件都会

🔍 定义

js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  // 1. 定义状态 (state)
  state: () => ({
    name: '张三',
    roles: ['admin', 'editor'],
  }),

  // 2. 定义计算属性 (getters)
  getters: {
    newName: (state) => {
      return state.name + '李四';
    }
  },

  // 3. 定义方法 (actions)
  actions: {
    // 事件函数,用于修改state状态
  },
});
js
// 组合式1:
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0, name: 'Eduardo' }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})
// 组合式2:
// export const useCounterStore = defineStore('counter', () => {
//   const count = ref(0)
//   const name = ref('Eduardo')
//   const doubleCount = computed(() => count.value * 2)
//   function increment() {
//     count.value++
//   }

//   return { count, name, doubleCount, increment }
// })

📝 state监听器(订阅)

js
// 订阅 state 变化
const counterStore = useCounterStore()
counterStore.$subscribe((mutation, state) => {
  // 每次 state 变化时,将最新的 state 存入 localStorage,做为持久化数据
  localStorage.setItem('counterState', JSON.stringify(state))
})

// 取消监听

🚀 使用

js
import { useCartStore } from '';

const cartStore = useCartStore();
console.log(cartStore.name); // 张三
console.log(cartStore.newName); // 张三李四
cartStore.name = '李四'; // 修改状态

向 getter 传递参数

js
// 组件里面getUserById(521)
export const useUserListStore = defineStore('userList', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users + userId;
    },
  },
})