uni-app开发-pinia状态管理集成封装

241 阅读1分钟
1. uniapp内置了pinia,无需手动安装
2. main.js中集成
import App from './App'
import * as Pinia from 'pinia';

// #ifndef VUE3 //不是vue3应用

import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue({
    ...App
})

app.$mount()

// #endif

 

// #ifdef VUE3 //是vue3应用

import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  
  app.use(Pinia.createPinia()); // 集成状态管理pinia
  
  return {
    app,
    Pinia, // 此处必须将 Pinia 返回
  }
}

// #endif
3. 封装(根目录下创建一个store文件夹,store文件夹中创建一个js文件用于封装store)
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state(){
    return {
      count:10
    }
  },
  
  actions: {
    increment() {
      this.count++
    },
  },
  
  getters:{//相当于计算属性
    num:(state)=>state.count
  }
});
4. 页面.vue文件中引入并使用
<template>

   <view class="g-container">
     详情页
     <view class="">
       {{counterStore.count}}
     </view>
     <button type="default" @click="counterStore.increment()">加一</button>
   </view>

</template>

<!--
   第一次进入组件时, goods为null,调用其属性报错
 -->

<script setup>
  import { ref } from "vue"
  import { onLoad } from '@dcloudio/uni-app'
  import { useCounterStore } from '../../store/counter.js'

  const counterStore = useCounterStore()
</script>

<style lang="scss"></style>