安装pinia
yarn add pinia
# 或者使用 npm
npm install pinia
使用
-
全局main.js 配置pinia
const app = createApp(App) #引入&使用pinia import {createPinia} from 'pinia' app.use(createPinia()) app.mount('#app')
-
语法1 store/numStore.js
/* num pinia模块 */ import {defineStore} from 'pinia' export const useNumstore = defineStore('numstore', { //state数据 state: () => { return { num: 10, } }, //getters getters: { doubleNum(state) { return state.num * 2 }, }, //actions actions: { //增加 increase() { this.num++ }, //减少 decrease() { this.num-- }, }, })
-
语法2 hooks语法
/* num pinia模块 */ import {defineStore} from 'pinia' import {ref,computed} from 'vue' export const useNumstore = defineStore('numstore', ()=>{ const num = ref(10) const doubleNum = computed(()=>num.value * 2) const increase = ()=>{ num.value++ } const decrease = ()=>{ num.value-- } return { num, doubleNum, increase, increase } })
-
使用
<template> <div> <h3>子组件</h3> <p>数据num:{{ num }}</p> <button @click="increase">+</button> <button @click="decrease">-</button> </div> </template> <script setup> #导出解构响应式函数 import {storeToRefs, computed} from 'pinia' #引入仓库 import {useNumstore} from '../../store/modules/numStore' #创建一个hooks 仓库实例 const $numStore = useNumstore() #函数直接解构 const {increase, decrease} = $numStore #数据需要响应式解构 const {num} = storeToRefs($numStore) #获取响应式数据方法2 简单 const num = computed(()=>$numStore.num) </script>