// 使用 Vue 3 和 Pinia 创建一个 store
// 首先,确保你已经安装了 Pinia
// npm install pinia
// 然后在你的项目中创建一个 store 文件,例如:stores/counter.js
import { defineStore } from 'pinia';
// 使用 defineStore 定义一个 store
export const useCounterStore = defineStore('counter', {
// state 是响应式的状态
state: () => ({
count: 0,
}),
// getters 类似于 Vue 的计算属性,用于派生状态
getters: {
doubleCount: (state) => state.count * 2,
},
// actions 用于定义改变 state 的方法
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
// 在 main.js 或 main.ts 中注册 Pinia
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
// 注册 Pinia
app.use(createPinia());
app.mount('#app');
// 在组件中使用 store
<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 './stores/counter';
// 获取 store 实例
const counter = useCounterStore();
</script>
defineStore
函数定义一个名为 counter
的 store。它包含三个主要部分:state
: 存储应用的状态。getters
: 用于派生状态,类似于 Vue 的计算属性。actions
: 包含可以改变状态的方法。main.js
)中注册 Pinia。useCounterStore
获取 store 实例,并在模板中使用其状态和方法。上一篇:vue eventsource
下一篇:vue @change
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站