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

Pinia状态管理工具速成

一、介绍
main.js展现了对Pinia的引用,这里与引用Vuex是类似的,而且并没有像Vuex一样在store/index.js在文件中进行相关的配置,而是直接的使用。

main.js

import './assets/main.css'import { createApp } from 'vue'
import { createPinia } from 'pinia'import App from './App.vue'
import router from './router'const app = createApp(App)app.use(createPinia())
app.use(router)app.mount('#app')

store/counter.js

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', () => {const count = ref(0)const doubleCount = computed(() => count.value * 2)function increment() {count.value++}return { count, doubleCount, increment }
})

export const useCounterStore = defineStore('counter', () => {})这里类似于Vuex中的modules

const count = ref(0)这里类似于Vuex中的state
const doubleCount = computed(() => count.value * 2)这里类似于Vuex中的getters

 function increment() {count.value++}这里类似于Vuex中的actions

mutation概念是不存在的,只要封装了的话就是actions



相较于Vuex更直观、简洁



二、Pinia实战案例

<script setup>
import { useCounterStore } from '../stores/counter'
const countStore = useCounterStore()
</script><template><div class="about"><h3>count:{{ countStore.count }}</h3><p>------------</p><h3>2*count:{{ countStore.doubleCount }}</h3><button @click="countStore.increment()">+1</button></div>
</template><style>
@media (min-width: 1024px) {.about {min-height: 100vh;display: flex;align-items: center;}
}
</style>

导入并创建示例
import { useCounterStore } from '../stores/counter'

const countStore = useCounterStore()

引用

<h3>count:{{ countStore.count }}</h3>

<p>------------</p>

<h3>2*count:{{ countStore.doubleCount }}</h3>

<button @click="countStore.increment()">+1</button>

 

http://www.xdnf.cn/news/294265.html

相关文章:

  • 认识并理解什么是链路层Frame-Relay(帧中继)协议以及它的作用和影响
  • 【C/C++】无锁编程——compare_exchange_strong
  • 第二章 - 软件质量
  • S100平台调试RS485/RS232
  • Python Cookbook-7.2 使用 pickle 和 cPickle 模块序列化数据
  • 【Python】 `os.getenv()` vs. `os.environ.get()`:环境变量获取方式的本质差异解析
  • Milvus(14):更改 Collections 字段、Schema 设计实践
  • (42)VTK C++开发示例 ---渲染不同颜色的20面体
  • 基于 jQuery 实现复选框全选与选中项查询功能
  • 【AI论文】KeySync:一种在高分辨率下实现无泄漏唇形同步的稳健方法
  • 开元类双端互动组件部署实战全流程教程(第1部分:环境与搭建)
  • 【自然语言处理与大模型】LlamaIndex的数据连接器和对话引擎
  • TS 函数中的类型兼容性
  • 20250505下载VLC for Android
  • 集合-探索
  • 观察者模式
  • 论文答辩讲稿脚本分享(附我自己用的版本)
  • Model Context Protocol (MCP) 技术解析
  • Kotlin中 StateFlow 或 SharedFlow 或 LiveData的区别
  • **集合**实验**
  • 基于SpringBoot的漫画网站设计与实现
  • 迭代器模式(Iterator Pattern)
  • Numpy随机分布
  • Lesson 17 Always young
  • Multi Agents Collaboration OS:专属多智能体构建—基于业务场景流程构建专属多智能体
  • 数据库MySQL学习——day9(聚合函数与分组数据)
  • 2025系统架构师---论软件可靠性设计范文
  • c++代码_加密_解密
  • 【了解】数字孪生网络(Digital Twin Network,DTN)
  • Sliding Window Attention(Longformer)