• Pinia 的基本使用


    Pinia 的主要特点

    安装 Pinia

    你可以通过 npm 或 yarn 来安装 Pinia。

    1. npm install pinia
    2. # 或者
    3. yarn add pinia
    配置 Pinia

    Vue 应用的入口文件(如 main.js 或 main.ts)中,你需要导入 createPinia 并与 Vue 应用实例进行绑定。

    1. import { createApp } from 'vue'
    2. import { createPinia } from 'pinia'
    3. import App from './App.vue'
    4. const app = createApp(App)
    5. const pinia = createPinia()
    6. app.use(pinia)
    7. app.mount('#app')
     
    创建 Store

    使用 Pinia,你可以通过 defineStore 函数来创建 store。每个 store 都是一个独立的实体,包含其自己的状态、getters 和 actions。

    1. import { defineStore } from 'pinia'
    2. export const useCounterStore = defineStore('counter', {
    3. state: () => {
    4. return { count: 0 }
    5. },
    6. getters: {
    7. doubleCount: (state) => state.count * 2,
    8. },
    9. actions: {
    10. increment() {
    11. this.count++
    12. },
    13. decrement() {
    14. this.count--
    15. },
    16. },
    17. })
    在组件中使用 Store

    在 Vue 组件中,你可以通过导入并使用刚才定义的 store 来访问其状态、getters 和 actions。

     

    1. <template>
    2. <div>
    3. <p>Count: {{ count }}</p>
    4. <p>Double Count: {{ doubleCount }}</p>
    5. <button @click="increment">Increment</button>
    6. <button @click="decrement">Decrement</button>
    7. </div>
    8. </template>
    9. <script>
    10. import { useCounterStore } from './stores/counter'
    11. export default {
    12. setup() {
    13. const counterStore = useCounterStore()
    14. return {
    15. count: counterStore.count,
    16. doubleCount: counterStore.doubleCount,
    17. increment: counterStore.increment,
    18. decrement: counterStore.decrement,
    19. }
    20. },
    21. }
    22. </script>

  • 相关阅读:
    不同数据库行号关联问题
    flutter TabBar指示器
    智能网联汽车云控系统第2部分:车云数据交互规范
    Android Radio实战——打开Tuner(十八)
    计算机毕业设计Python+Django的个人博客系统(源码+系统+mysql数据库+Lw文档)
    malloc和new的本质区别
    LeetCode 290. Word Pattern
    Go语言Web开发入门指南
    常见的一些小函数集合
    01.shiro入门
  • 原文地址:https://blog.csdn.net/2301_78133614/article/details/140465087