• vue3的状态管理方案pinia/类似于vue2的VueX


    pinia官网:https://pinia.vuejs.org/
    pinia菠萝挺不错,简单又灵活。
    1.安装:yarn add pinia 或者 npm install pinia,全局加 --location=global
    2.注册使用 main.js
    import { createApp } from 'vue'
    import App from './App.vue'
    import { createPinia } from 'pinia'
    
    const app = createApp(App);
    const pinia = createPinia();
    app.use(pinia);
    app.mount('#app');
    //异常统一处理
    app.config.errorHandler = (err) => {
        /* handle error */
        console.log("exception:" + err);
    }
    

    3.在src目录下创建store文件夹,然后创建counter.js文件,名字自己定,官网参考:https://pinia.vuejs.org/core-concepts/
    方式一 options stores

    import { defineStore } from 'pinia'
    export const useCounterStore = defineStore('counter', {
        //方式一
        // state: () => {
        //     return { count: 0,user_name:'jay.star' }
        // },
        //方式二
        state: () => ({ count: 0, user_name: 'jay.star' }),
        //相当于计算属性 computed
        getters: {
            doubleCount: (state) => state.count * 2,
        },
        //相当于 methods
        actions: {
            increment() {
                this.count++
            },
        },
    });
    

    方式二setup stores

    import { defineStore } from 'pinia'
    import { ref,computed } from 'vue';
    export const useCounterStore = defineStore('counter', () => {
        const count = ref(0);
        const user_name = ref("jay.star");
        //getters
        const doubleCount = computed(() => count.value * 2);
        //即 actions 和 methods
        function increment() {
            count.value++
        }
        return { count, user_name, doubleCount, increment };
    });
    

    4.使用 getters 可以直接 {{counter.doubleCount}}

    <script setup>
    import { useCounterStore } from "@/stores/counter";
    const counter = useCounterStore();
    // 直接修改
    counter.count++;
    // $patch
    counter.$patch({ count: counter.count + 1 });
    // action
    counter.increment();
    </script>
    

      可以定义多个,一般是再建一个文件,比如 userinfo.js,然后里面再写一个 export const useUserInfoStore = defineStore('userinfo',{...});
    更多参考官网

  • 相关阅读:
    计算机编码总结
    将TOMCAT设置成为NT服务
    java 操作oracle 序号器相关
    java事件机制
    c# Semaphore(信号量)
    C#中异步和多线程的区别
    c#多线程调用有参数的方法
    解决TCP网络传输“粘包”问题
    高性能socket设计实现
    c# Buffer学习笔记
  • 原文地址:https://www.cnblogs.com/xsj1989/p/16620664.html
Copyright © 2020-2023  润新知