// store/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
// 状态
state: () => ({
count: 0,
}),
// 获取器 (计算属性)
getters: {
doubleCount: (state) => state.count * 2,
},
// 修改状态的方法
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
// 使用 Pinia
app.use(createPinia());
app.mount('#app');
// 在组件中使用
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
<button @click="counter.decrement">Decrement</button>
</div>
</template>
<script setup>
import { useCounterStore } from './store/counter';
const counter = useCounterStore();
</script>
定义 Store:
defineStore 创建一个名为 counter 的 store。state 定义了存储的状态,这里是 count。getters 类似于 Vue 的计算属性,用于派生状态,例如 doubleCount。actions 是修改状态的方法,例如 increment 和 decrement。注册 Pinia:
main.js 中,创建 Vue 应用实例并使用 createPinia() 注册 Pinia。在组件中使用 Store:
<script setup> 语法导入并使用 useCounterStore。counter 访问 store 中的状态和方法。这样就可以在 Vue 组件中方便地管理和共享状态。
上一篇:vue3中使用swiper
下一篇:props vue
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站