Vue3中使用Pinia

405 阅读1分钟

官网

pinia.vuejs.org/

与vuex差别

  • 只有state,getters, actions
  • 分模块不需要modules
  • 体积更小、性能更好
  • 可以直接修改state数据

安装

npm i pinia

使用

例子:

  1. main.js中引用
...
import { createPinia } from "pinia";
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
  1. 新建./store/user.js(模块化:在./store中编写多个模块的js文件)
import { defineStore } from 'pinia'
export const userStore = defineStore('user', {
  state: () => {
      return {
          age: 18,
          firstname: 'Zheng'
      }
  },
  getters: {
      name() {
          console.log('getters')
          return (this.firstname + ' Hongling')
      }
  },
  actions: {
      plusAge(val) {
        console.log('actions')
        this.age += val
      }
  }
})
  1. vue模板中调用(模块化:引入./store中的所需模块的js文件,并调用)
import { storeToRefs } from "pinia";
// 引入store配置文件
// user模块
import { userStore } from "@/store/user.js";
const user = userStore()

// 调用state、getters数据
let {age, firstname, name} = storeToRefs(user);

function handleClick() {
  // 单个改值
  // age.value += 1

  // 批量改值
  user.$patch(state => {
      state.age ++
      state.firstname = '郑'
  })
}

function add() {
  // 调用store中的actions方法
  user.plusAge(200)
}

function reset() {
  // 调用store自带的reset重置方法
  user.$reset()
}

持久化存储

  1. 安装持久化存储插件
npm i pinia-plugin-persist
  1. 创建./store/index.js
import { createPinia } from 'pinia'
// 引入pinia的持久化存储插件
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
// 使用插件
store.use(piniaPluginPersist)

export default store
  1. 修改./main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// import { createPinia } from "pinia";

const app = createApp(App)

app.use(router)
app.use(store)
// app.use(createPinia())

app.mount('#app')
  1. 修改需要持久存储的模块的配置文件,例如:用户模块./store/user.js
import { defineStore } from 'pinia'
export const userStore = defineStore('user', {
  state: () => {...},
  getters: {...},
  actions: {...},
  // 数据缓存
  persist: {
      // 开启
      enabled: true,
      // 配置缓存
      strategies: [
          {
              key: 'cur_user', // 缓存key值,默认为该模块的id值,即'user'
              storage: localStorage, // 缓存位置,默认在session
              paths: ['firstname'], // 缓存字段,默认缓存模块的所有state字段
          }
      ]
  }
})