• uni-app开发微信小程序 vue3写法添加pinia


    说明

    使用uni-app开发,选择vue3语法,开发工具是HBliuderX。虽然内置有vuex,但是个人还是喜欢用Pinia,所以就添加进去了。
    Pinia官网连接

    添加步骤

    第一步:

    在项目根目录下执行命令:

    npm install pinia

    第二步:

    配置main.js文件

    // #ifdef VUE3
    import { createSSRApp } from 'vue'
    import * as Pinia from 'pinia';		// 配置pinia第一句
    export function createApp() {
      const app = createSSRApp(App)
      // 状态管理
      const store = Pinia.createPinia();	// 配置pinia第二句
      // 持久化
      app.use(store);						// 配置pinia第三句
      return {
        app,
    	Pinia								// 配置pinia第四句
      }
    }
    // #endif
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    第三步,使用:

    创建store文件夹、创建store/index.js

    import {
    	appStore
    } from "./modules/app.js"
    
    const useStore = () => ({
    	app: appStore(),
    });
    
    export default useStore;
    /**
     * 用法
     * 	import useStore from "@/store/index.js"
    	const {
    		app
    	} = userStore();
    	
    	let app = app.appIndex
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    然后创建store/modules/app.js文件

    import {
    	defineStore
    } from 'pinia'
    export const appStore = defineStore('app', {
    	unistorage: true, // 是否持久化到内存
    	state: () => {
    		return {
    			// 测试
    			appIndex: 999,
    		}
    	},
    	actions: {}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    像下面这个样子:
    在这里插入图片描述

    使用:

    在js文件夹下导入使用即可

    import useStore from "@/store/index.js"
    	const {
    		app
    	} = userStore();
    	
    	let app = app.appIndex
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    完整一点的示例:

    <script>
    	import useStore from "@/store/index.js"
    	const {app} = useStore();
    	export default {
    		data() {
    			return {
    				text:"",
    			}
    		},
    		methods: {
    			getText(){
    				this.text = app.appIndex;
    			}
    	}
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    如果有更好的方法,欢迎大家一起讨论!

  • 相关阅读:
    DDPM的学习
    题目 1311: 数字三角形
    mongodb备份还原指南
    stream()流的一些常用方法
    分析:「羊了个羊」为什么能在超级App出圈
    天视通等小众冷门摄像机接入安防监控系统EasyCVR平台的常见兼容问题及解决方法
    C++等级3题
    C++入门(1)
    OK3568 forlinx系统编译过程及问题汇总
    MybatisPlus 4 DML 编程控制 4.4 乐观锁
  • 原文地址:https://blog.csdn.net/qq_43813351/article/details/134439865