Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 使用pinia

作者:嗜血苍狼   发布日期:2025-04-13   浏览:68

// 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>

解释说明:

  1. 创建 Pinia 实例:在 main.js 中,我们首先导入了 createPinia 函数,并通过 app.use(createPinia()) 将 Pinia 实例挂载到 Vue 应用中。

  2. 定义 Store:在 store/counter.js 文件中,我们使用 defineStore 定义了一个名为 main 的 Store。这个 Store 包含了状态 (state)、获取器 (getters) 和动作 (actions)。

  3. 状态管理

    • state:存储应用的状态,例如 count
    • getters:用于派生状态,类似于 Vue 的计算属性。这里我们定义了一个 doubleCount 获取器,返回 count 的两倍。
    • actions:用于定义改变状态的方法。这里我们定义了一个 increment 方法,用于递增 count
  4. 在组件中使用 Store:在组件的 <script setup> 中,我们通过 useCounterStore 来获取 Store 实例,并将其绑定到模板中的数据和事件上。

  5. 模板绑定:在模板中,我们展示了 countdoubleCount 的值,并通过按钮点击触发 increment 方法来更新状态。

上一篇:vue alert

下一篇:vue process.env.node_env

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站