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

vue pinia

作者:铁打的心,也会穿孔,   发布日期:2026-05-12   浏览:52

// store/counter.js
import { defineStore } from 'pinia';

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

// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);

// 创建并挂载 Pinia 实例
app.use(createPinia());

app.mount('#app');

// 在组件中使用
<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>
import { useCounterStore } from './store/counter';

export default {
  setup() {
    // 使用 store
    const counter = useCounterStore();
    return { counter };
  },
};
</script>

解释说明

  1. 创建 Store:

    • 使用 defineStore 函数创建一个名为 counter 的 store。
    • state 定义了 store 的初始状态。
    • getters 用于派生状态,类似于 Vue 的计算属性。
    • actions 用于定义改变状态的方法。
  2. 注册 Pinia:

    • main.js 中创建并注册 Pinia 实例,使其可以在整个应用中使用。
  3. 在组件中使用 Store:

    • 使用 useCounterStore 钩子函数获取 store 实例,并在模板中使用其状态和方法。

上一篇:vue3 axios

下一篇:vue3 defineexpose

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

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

Laravel 中文站