pinia状态管理的使用
小于 1 分钟
pinia状态管理的使用
main.js配置
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';
export function createApp() {
const app = createSSRApp(App);
app.use(Pinia.createPinia());
return {
app,
Pinia, // 此处必须将 Pinia 返回
};
}
创建一个pinia
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 };
},
// 也可以这样定义
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++;
},
},
});
组件和页面使用
<template>
<view>
<view>{{count}}</view>
<button @click="setNum">点击</button>
</view>
</template>
<script setup>
// 导入ref响应数据
import {ref} from 'vue'
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
let count = ref(0)
const setNum = ()=>{
counter.increment()
count.value = counter.count
}
</script>