main.ts
import { createApp } from "vue";
import { createPinia } from "pinia";
import "./style.css";
import App from "./App.vue";
const pinia = createPinia();
createApp(App).use(pinia).mount("#app");
1.定义store(state+action)数据+方法
组件counter
// 定义Store(state + action)
// 创建计数器store
import { defineStore } from "pinia";
import { ref } from "vue";
//counter模块名
export const userCounterStore = defineStore("counter", () => {
// 数据state
const count = ref(0);
// 修改数据的方法action
const increment = () => {
count.value++;
};
// 以对象的方式return出去供组件使用
return {
count,
increment,
};
});
2.组件使用store
app.vue
<script setup lang="ts">
// 导入一个use打头的方法
import { userCounterStore } from "./store/counterStore";
// 执行方法得到store实例对象
const countStore = userCounterStore();
console.log(countStore);
</script>
<template>
<div>
<button @click="countStore.increment">{{ countStore.count }}</button>
</div>
</template>