当前位置: 首页 > news >正文

vue3中pinia基本使用

一、安装以及引入

  • 安装:npm install pinia
  • main.js文件:
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";const pinia = createPinia()
const app = createApp(App)
app.use(pinia).mount("#app");

二、使用

新建store/Count/index.js

import { defineStore } from "pinia";
import { personStore } from "../Person/index";
export const useCounterStore = defineStore('counter', {// state: ()=>({name: 'alice',count: 0}),state: () => {return {count: 10,content: '~',users: [{name: 'alice', id: 1},{name: 'jack', id: 2},{name: 'rose', id: 3},]}},getters: { doubleCount: (state) => state.count * 2,// doublePlusOne:(state)=> state.doubleCount+1doublePlusOne() {return this.doubleCount + 1 // 可以访问其他getter},getUserById: (state) => { //  getter是计算属性 不可以向getter传递参数,可以从getter返回函数 给该函数可以传递参数return (userId) => state.users.find((user) => user.id === userId)},// 访问其他storegetOtherStoreName:(state)=>{const perStore=personStore()return perStore.username+state.content}},actions: {increment() {this.count++},randomizeCounter(){this.count=Math.round(100*Math.random())}}
})

新建store/Person/index.js:

import { defineStore } from "pinia";
export const personStore = defineStore('person', {state: () => {return {username: 'alice',age: 18,}},getters: {getName: (state) => `姓名:${state.username}`},actions: {changeName() {this.username = this.username + '~'}}
})

App.vue文件使用:

<template><div class="app"><ul><li> count:{{ countStore.count }} {{ countStore.content }}</li><li>double: {{ countStore.doubleCount }}</li><li>double+1: {{ countStore.doublePlusOne }}</li></ul><div>{{ countStore.getUserById(3) }}</div></div>
</template><script setup name="App">
import { useCounterStore } from "./store/Count";
import { computed } from "vue";const countStore = useCounterStore();// 作为action的increment可以直接解构
const {increment}=countStoreconst doubleValue = computed(() => countStore.doubleCount);
</script>

http://www.mrgr.cn/news/97639.html

相关文章:

  • 【扩展KMP】P10634 BZOJ2372 music |省选-
  • C++进阶笔记第二篇:引用
  • 智能设备运行监控系统
  • FreeRTOS临界区
  • CentOS8.5 安装 LLaMA-Factory
  • openEuler24.03 LTS下安装Flink
  • 查看手机在线状态,保障设备安全运行
  • SpringDoc【使用详解】
  • Dev C++下载及安装
  • fpga系列 HDL:跨时钟域同步 4-phase handshake(四相握手通信协议,请求-确认机制)浅释与代码实现
  • 嵌入式---加速度计
  • 搭建hadoop集群模式并运行
  • SearXNG
  • MCP基础学习一:MCP概述与基础
  • Linux 性能调优之CPU调优认知
  • 【回眸】Linux 内核 (十三)进程间通讯 之 共享内存
  • QML Loader:动态加载与控件创建
  • MCP-Playwright: 赋予AI模型操控浏览器的能力
  • c# 数据结构 链表篇 有关单链表的一切
  • 力扣hot100_回溯(2)_python版本