安装 :
npm install pinia
state: 状态。
actions: 修改状态(包括同步和异步,Pinia 中没有 mutations)。
getters: 计算属性。
main.ts :
import { createApp } from 'vue'
import './style.css'
import ElementPlus from 'element-plus'
import locale from "element-plus/lib/locale/lang/zh-cn";//element-plus中文版
import App from './App.vue'
import router from "./router/index"
import 'element-plus/theme-chalk/index.css'
import { createPinia } from 'pinia'
// 创建pinia实例
const pinia = createPinia()
const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000,locale }) //element-plus中文版,加入locale
app.use(router).use(pinia).mount('#app')
store/main.ts :
import { defineStore } from 'pinia'
export const useMainStore = defineStore('main', {
state: () => {
return {
count: 1,
users:[{id:1}]
}
},
getters: {
doubleCount: (state) => state.count * 2,
doublePlusOne(): number {
return this.count * 2 + 1
},
},
actions: {
addCount() {
this.count++
}
}
})
index.vue
<template>
<div>
{{ mainStore.count }}~{{ count }}<br/>
{{ mainStore.doubleCount }}~{{ mainStore.doublePlusOne }}<br/>
<button @click="getStore">+事件</button>
<button @click="mainStore.addCount">调用actions的addCount方法</button>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useMainStore } from '@/store/main';
const mainStore = useMainStore()
// 体验通过解构获取 pinia 的 state,解构出来的值不是响应式的
// 将 pinia 实例对象通过 storeToRefs 包裹起来的时候,里面的值就是响应式的了
const { count } = storeToRefs(mainStore)
// 按钮点击事件
const getStore = () => {
mainStore.count++
}
</script>