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>
相关推荐
滔滔不绝tao3 分钟前
自动化测试常用函数
前端·css·html5
LvManBa5 分钟前
Vue学习记录之三(ref全家桶)
javascript·vue.js·学习
码爸31 分钟前
flink doris批量sink
java·前端·flink
深情废杨杨32 分钟前
前端vue-父传子
前端·javascript·vue.js
工业互联网专业1 小时前
毕业设计选题:基于springboot+vue+uniapp的驾校报名小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
J不A秃V头A2 小时前
Vue3:编写一个插件(进阶)
前端·vue.js
司篂篂2 小时前
axios二次封装
前端·javascript·vue.js
宇文仲竹3 小时前
edge 插件 iframe 读取
前端·edge
Kika写代码3 小时前
【基于轻量型架构的WEB开发】【章节作业】
前端·oracle·架构