基础知识系列(十五):Vue3的Pinia的基本使用

在App.vue中,写

<template>
  <div>
    <h1>{{ count }}</h1>   <!-- mainStore.$state.count mainStore.count --> 
    <h1>{{ name }}</h1>
    <h1>{{ fullName }}</h1>
    <button @click="add">按钮自增10</button>
  </div>
</template>

<script setup>
  import { storeToRefs } from 'pinia';
  import { useMainStore } from './store'
  const mainStore = useMainStore()
  // 不要轻易解构响应式对象
  const {count,name,fullName} = storeToRefs(mainStore)
  function add(){
    mainStore.addCount(10) 
  }
</script>

在main.js中,写

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
createApp(App).use(pinia).mount('#app')

在store文件夹的index.js文件,其中写

import {defineStore} from 'pinia'
import {ref} from 'vue'

// 选项式API
// const useMainStore = defineStore('main',{
//     state:()=>{
//         return{
//             count:0,
//             name:'peiqi'
//         }
//     },
//     actions:{
//         addCount(number){
//             //this.count += number
//             setTimeout(()=>{
//                 this.count += number
//             },1000)
//         }
//     },
//     getters:{
//         fullName(){
//             return '小猪' + this.name
//         }
//     }
// })

// 组合式API
const useMainStore = defineStore('main',()=>{
    const count = ref(0)
    const addCount = ()=>{
        count.value++
    }
    return{
        count,
        addCount
    }
})
export {useMainStore}

PS:1.pnpm i pinia;2.useXXXXX是用于常见实例的命名方式;3.Vue2是选项式API,Vue3是组合式API

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值