pinia在vue3中的使用

下载pinia

复制代码
   yarn add pinia

导入pinia

javascript 复制代码
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

定义pinia

复制代码
  ### option方式

  1. Vue的选项式 API 类似,我们也可以传入一个带有state、actions与getters属性的Option对象。  
     state是store的数据 (data),getters是store的计算属性(computed),而actions则是方法(methods)。

     ```javascript
     export const useCounterStore = defineStore('counter', {
       state: () => ({ count: 0, name: 'Eduardo' }),
       getters: {
         doubleCount: (state) => state.count * 2,
       },
       actions: {
         increment() {
           this.count++
         },
       },
     })
     ```
复制代码
  ### setup方式

  1. ref()就是state属性,computed()就是getters,function()就是actions。

     ```javascript
     export const useCounterStore = defineStore('counter', () => {
       const count = ref(0)
       const doubleCount = computed(() => count.value * 2)
       function increment() {
         count.value++
       }

       return { count, doubleCount, increment }
     })
     ```

使用store

  1. vue3使用pinia,这里使用了<script setup>

    javascript 复制代码
    <script setup>
    import { useCounterStore } from '@/stores/counter'
    // 可以在组件中的任意位置访问 `store` 变量 ✨
    const store = useCounterStore()
    </script>
  2. 详细使用

    javascript 复制代码
    <script setup>
    import { useCounterStore } from '@/stores/counter'
    import { computed } from 'vue'
    
    const store = useCounterStore()
    // ❌ 这将不起作用,因为它破坏了响应性
    // 这就和直接解构 `props` 一样
    const { name, doubleCount } = store
    name // 将始终是 "Eduardo"
    doubleCount // 将始终是 0
    setTimeout(() => {
      store.increment()
    }, 1000)
    // ✅ 这样写是响应式的
    // 💡 当然你也可以直接使用 `store.doubleCount`
    const doubleValue = computed(() => store.doubleCount)
    </script>
相关推荐
万少1 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站3 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫6 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊6 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter6 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折6 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码16 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial6 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js