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

vue3 definestore

作者:二分醒amor   发布日期:2025-04-01   浏览:139

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

解释说明:

  1. 安装 Pinia:首先需要通过 npm 安装 Pinia。
  2. 定义 Store:使用 defineStore 函数定义一个名为 counter 的 store。它包含三个主要部分:
    • state: 存储应用的状态。
    • getters: 用于派生状态,类似于 Vue 的计算属性。
    • actions: 包含可以改变状态的方法。
  3. 注册 Pinia:在主应用文件(如 main.js)中注册 Pinia。
  4. 使用 Store:在组件中通过 useCounterStore 获取 store 实例,并在模板中使用其状态和方法。

上一篇:vue eventsource

下一篇:vue @change

大家都在看

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