<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { defineComponent, computed } from 'vue';
import { useStore } from '../stores/counterStore';
export default defineComponent({
setup() {
// 使用Pinia中的store
const store = useStore();
// 使用getters
const count = computed(() => store.count);
// 使用Actions
function increment() {
store.increment();
}
// 将count和increment返回到模板中
return { count, increment };
}
});
</script>这个例子展示了如何在Vue 3组件中使用Pinia状态管理库。首先,我们从store导入useStore,然后在setup函数中调用它。接着,我们使用computed来创建一个响应式的属性count,它依赖于store中的count getter。最后,我们定义了一个函数increment来调用store中的increment action。在模板中,我们可以直接使用count和increment。