Use pinia in uni-app

Table of contents

What are Pinias?

uni-app uses Pinia

Reference pinia in main.js

Create and register modules

Define the pinia way

Option options way to define pinia

Use the pinia option options method in the page

Functional way to define pinia

The pinia defined in the function mode on the page


What are Pinias?

Pinia (pronounced  /piːnjʌ/as in English  peenya) is a repository for Vue that allows you to share state across components, pages.

On the server side as well as in small single-page applications, you can also get a lot of benefits from using Pinia:

  • Devtools support

    • Timeline to track actions and mutations

    • Display the Store they use in the component

    • Time travel for easier debugging

  •  Hot Module Replacement

    • Modify the Store without reloading the page

    • The current state can be maintained during development

  • Provide proper TypeScript support and auto-completion for JS developers.

picture

uni-app uses Pinia

uni-app has Pinia built in. Vue 2 projects are not supported yet

Using HBuilder X does not require manual installation, it can be used directly. Using the CLI requires manual installation, execution  yarn add [email protected] or  npm install [email protected].

uni-app has built-in state management of vuex and pinia, which can be used without installation.

Suggested project structure

├── pages
├── static
└── stores // 注意此处
    └── counter.js
├── App.vue
├── main.js
├── manifest.json
├── pages.json
└── uni.scss

Reference pinia in main.js

mian.js  references and uses pinia

//导入pinia
import * as Pinia from  'pinia'

// 创建Pinia实例  // 将pinia实例挂载到vue实例上 
app.use(Pinia.createPinia());

return {
    app,
    Pinia, // 此处必须将 Pinia 返回
} 

main.js complete code

// #ifndef VUE3
import Vue from 'vue'
import App from './App' 

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'

//导入pinia  
import * as Pinia from  'pinia'

import App from './App.vue'
export function createApp() {
    const app = createSSRApp(App)

    // 创建Pinia实例  // 将pinia实例挂载到vue实例上 
    app.use(Pinia.createPinia());

    return {
        app,
        Pinia, // 此处必须将 Pinia 返回
    }
}
// #endif

Please pay special attention to the pinia reference position, otherwise an error will be reported

picture

Create and register modules

在需要使用全局状态管理的地方,你可以创建一个或多个Pinia模块。每个模块代表一个具体的状态管理单元。

project, new stores文件夹, for storage 创建和注册的模块

picture

In stores文件夹, create a new js file ( useCounterStore.js) for storage 创建和注册的模块

picture

Define the pinia way

选项options方式 define pinia

useCounterStore.jsWrite the following code in

import { defineStore } from 'pinia'

// 定义仓库有两种定义方式

// 01 选项options方式
export const useCounterStore = defineStore('counter', {
  // 定义状态
      state:()=>({count:5}),
      // 计算数据
      getters:{
          doubleCount:(state)=>state.count*2
      },
      // 动作支持异步
      actions:{
          setCount(v){
              this.count = v;
          }
      }
})

Use the pinia option options method in the page

<template>
    <view>
        pinia 大菠萝doubleCount:{
   
   {doubleCount}}
        <button>{
   
   {count}}</button>
    </view>
</template>

<script>
import {useCounterStore} from "@/stores/useCounterStore.js
// map方泛
import {mapState} from 'pinia';

export default {
    data(){},
    computed: function(){
        // 把pinia 的state映射到页面
        ...mapState(useCounterStore,["count","doubleCount"]
    } ,
    methods:{
        // 把pinia的方法映射到页面
        ...mapActions(useCounterStore,["setCount"])
    }
</script>

This way of writing is very similar to vuex, but without the mutation method

函数方式 define pinia

Create a new js file ( useColorStore.js) and define pinia

// 导入定义仓库的方法
import {defineStore} from 'pinia';

// 导入响应式和计算
import {ref} from 'vue'
const  useColorStore = defineStore("color",()=>{
    // 定义一个状态颜色为 默认红色
    const color=ref('red');
    // 定义一个设置状态的方法
    const setColor = v=>{
        color.value = v;
    }
    // 导入
    return {color,setColor}
}) 

export default useColorStore;          

Use  函数方式 the defined pinia in the page

<template>
    <view class="container">
        <button @click="setColor">更改颜色</button> 
        
        <view :style="'background:'+colorStore.color">
            v-show="isShow"
        </view>
    </view>
</template>

<script setup>
    import useColorStore from '@/stores/useColorStore.js'
    const colorStore = useColorStore() 
    const setColor = () => { 
        colorStore.setColor('#333')
    }  
</script> 

<style lang="less" scoped> 
    .container {
        padding: 0 20px 20px;
        font-size: 14px;
        line-height: 24px;
    }
</style>

misunderstanding

picture

reference documents

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/132270165