pinia是vue2,vue2 尤其是vue3官方推荐的状态管理器,和vuex类似,但使用起来更为简单,
概念:
state:定义响应式共享变量
getter:相当于计算属性
actions:相当于方法
npm安装
npm install pinia
创建pinia ,注入到app实例中
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
定义store
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('double-counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count+=2
},
},
})
state属性值为函数,返回值为一个对象
使用store
defineStore创建的实例是全局共享的,是单例的。
<script setup lang="ts">
import { useCounterStore } from '@/stores/double-counter';
import Demo from './components/Demo.vue';
const counter= useCounterStore()
</script>
<template>
<div class="wrapper">
<h3>{{counter.count}}</h3>
<button @click="counter.count++">点我</button>
<Demo />
</div>
</template>
<style scoped></style>