uniapp中使用pinia

可视化创建的项目自带安装pinia,项目中可以直接用,cli脚手架安装的需要npm安装pinia

1.可视化项目使用pinia

在main.js引入并注册pinia

import App from './App'

import { createSSRApp } from 'vue'
import * as Pinia from 'pinia'
export function createApp() {
  const app = createSSRApp(App)
  // 注册pinia
  app.use(Pinia.createPinia())
  return {
    app,
    Pinia
  }
}

在根目录下新建store文件,新建子文件counter.js

import {defineStore} from 'pinia'
// name:counter,是store的名称,需要保证唯一性,或者唯一的ID
export const useCounterStore=defineStore('counter',{
    state:()=>{
        return{
            count:700,
        }
    },
    actions:{
        // 同步
        increment(){
            this.count++
        },
        decrement(){
            this.count--
        }
    }
})

在项目中使用pinia

<template>
    <view>
        <view class="">
            {{count}}
        </view>
        <button @click="addCount">count++</button>
        <button @click="subCount">count--</button>
    </view>
</template>

<script setup>
    import {storeToRefs} from 'pinia'
    import {useCounterStore} from '@/store/counter.js' 
    const counterStore=useCounterStore()
    // storeToRefs获取pinia的响应式对象
    const {count}=storeToRefs(counterStore)
    function  addCount(){
        counterStore.increment()
    }
    function subCount(){
        counterStore.decrement()
    }
</script>

<style>

</style>
 

  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值