// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
// 创建 Pinia 实例并挂载到 Vue 应用中
app.use(createPinia())
app.mount('#app')
// store/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('main', {
// 状态
state: () => ({
count: 0,
}),
// 获取器 (类似于 Vue 的 computed)
getters: {
doubleCount: (state) => state.count * 2,
},
// 动作 (类似于 Vue 的 methods)
actions: {
increment() {
this.count++
},
},
})
// 在组件中使用 Pinia Store
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from './store/counter'
// 使用 Pinia Store
const counter = useCounterStore()
</script>
创建 Pinia 实例:在 main.js 中,我们首先导入了 createPinia 函数,并通过 app.use(createPinia()) 将 Pinia 实例挂载到 Vue 应用中。
定义 Store:在 store/counter.js 文件中,我们使用 defineStore 定义了一个名为 main 的 Store。这个 Store 包含了状态 (state)、获取器 (getters) 和动作 (actions)。
状态管理:
state:存储应用的状态,例如 count。getters:用于派生状态,类似于 Vue 的计算属性。这里我们定义了一个 doubleCount 获取器,返回 count 的两倍。actions:用于定义改变状态的方法。这里我们定义了一个 increment 方法,用于递增 count。在组件中使用 Store:在组件的 <script setup> 中,我们通过 useCounterStore 来获取 Store 实例,并将其绑定到模板中的数据和事件上。
模板绑定:在模板中,我们展示了 count 和 doubleCount 的值,并通过按钮点击触发 increment 方法来更新状态。
上一篇:vue alert
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站