vue3-pinia状态管理

107 阅读1分钟

1.将pinia挂载到main.js上

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
  1. src下创建store/modules/counter.js,存储不同模块的数据
// 使用组合式写法导出useCounterStore
//defineStore的第一个选项是模块的id标识,第二个选项是配置项
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCounterStore = defineStore("counter", () => {
// state
  const count = ref(0)
  
  // action
  function increment() {
    count.value++
  }
  function decrease() {
    if (count.value == 0) return
    count.value--
  }
  
  //getter
  const countStr = computed(() => `数量是${count.value}个`)
  return { count, increment, decrease, countStr }
});
  1. 页面引入模块进行使用
<template>
    <div class="flexR-sc">
        <button @click="minus">-</button>
        <div class="box">{{ counter.count }}</div>
        <button @click="plus">+</button>
    </div>
    <div class="total">{{ counter.countStr }}</div>
</template>
<script setup>
import { useCounterStore } from '@/store/modules/counter.js'
const counter = useCounterStore()

// 进行数据初始化化操作
counter.$patch({ count: counter.count + 1 }) // counter.count++

function plus() {
    counter.increment()
}
function minus() {
    counter.decrease()
}
</script>
<style>
.box {
    padding: 0 .5rem;
}
.total{
    font-size: 2rem;
}
</style>

重置state

组合式

export const useCounterStore = defineStore("counter", () => {
  const count = ref(0)
  function increment() {
    count.value++
  }
  function decrease() {
    if (count.value == 0) return
    count.value--
  }
  function $reset(){
    count.value = 0
  }
  const countStr = computed(() => `数量是${count.value}个`)
  return { count, increment, decrease, countStr,$reset }
});


function reset() {
   counter.$reset()
}

选项式

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

订阅state

const counter = useCounterStore()
counter.$subscribe((mutation, state) => {
    console.log('123', mutation)
    console.log('456', state)

}, { detached: true })

detached: true 订阅器即便在组件卸载之后仍会被保留

mutation.type 'direct' | 'patch object' | 'patch function'

mutation.storeId 和 cartStore.$id 一样

mutation.payload
mutation.type === 'patch object'的情况下才可用,传递给 cartStore.$patch() 的补丁对象。