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

pinia vue3

作者:淡漠伤悲   发布日期:2025-03-25   浏览:57

// 引入 Pinia 和 Vue 3 的相关模块
import { createPinia, defineStore } from 'pinia';
import { createApp } from 'vue';

// 创建一个 Pinia 实例
const pinia = createPinia();

// 定义一个 Store,命名为 'counter'
const useCounterStore = defineStore('counter', {
  // state 是存储数据的地方
  state: () => ({
    count: 0,
  }),
  // getters 类似于 Vue 的计算属性,用于派生状态
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  // actions 用于定义改变 state 的方法
  actions: {
    increment() {
      this.count++;
    },
  },
});

// 创建 Vue 应用实例,并挂载 Pinia
const app = createApp({
  setup() {
    // 在组件中使用 counter store
    const counter = useCounterStore();
    return { counter };
  },
});

// 将 Pinia 插件安装到 Vue 应用中
app.use(pinia);

// 挂载应用到 DOM 中
app.mount('#app');

解释说明:

  1. 引入模块:首先引入了 createPiniadefineStorecreateApp,这些是 Pinia 和 Vue 3 的核心模块。
  2. 创建 Pinia 实例:使用 createPinia() 创建了一个 Pinia 实例。
  3. 定义 Store:通过 defineStore 定义了一个名为 counter 的 Store,包含 state(存储数据)、getters(派生状态)和 actions(改变状态的方法)。
  4. 创建 Vue 应用:使用 createApp 创建了一个 Vue 应用实例,并在 setup 函数中使用了 useCounterStore 来访问 Store。
  5. 安装 Pinia:通过 app.use(pinia) 将 Pinia 插件安装到 Vue 应用中。
  6. 挂载应用:最后,将应用挂载到 DOM 中的 #app 元素上。

这段代码展示了如何在 Vue 3 项目中集成 Pinia 并使用它来管理状态。

上一篇:npm 安装vue3

下一篇:vue表格插件

大家都在看

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 中文站