美文网首页IT 全栈开发
vue3 状态管理 之 Pinia --- 三分钟放弃

vue3 状态管理 之 Pinia --- 三分钟放弃

作者: 醋留香 | 来源:发表于2022-10-05 11:56 被阅读0次
    1. 在项目中安装 pinia 模块,并在 main.js 中进行导入和 use
    import {createPinia} from "pinia"
    
    const app = createApp(App)
    app.use(createPinia())
    
    1. 创建一个用来做状态管理的js文件
    // /stores/counter.js
    import { defineStore } from "pinia";
    
    export const useCounterStore = defineStore("counter" , {
        state: () => {
            return {
                count: 6
            }
        },
        actions: {
            increment(){
                this.count++
            }
        }
    })
    
    1. 在任何一个组件中进行使用 比如: test.vue 中
    
    
    import {useCounterStore} from "@/stores/counter"
    var counter = useCounterStore()
    
    // 我们可以采用下面三种办法来修改 count 的值
    // 第一种
    counter.count++
    
    // 第二种
    counter.$patch({
        count: counter.count + 1
    })
    
    // 第三种
    counter.increment()
    
    // 但不管是哪一种, 只要在 非顶层作用域 进行修改, 则不会触发界面更新
    // 比如 我们放在 定时器  或 按钮点击事件中进行修改
    
    // 在定时器中修改, 界面不会更新
    setInterval(() => {
        console.log("时间到, 开始增加。。。。")
        
        counter.count++
    
        counter.$patch({
            count: counter.count + 1
        })
    
        counter.increment()
    
        console.log(counter.count)
    }, 1000);
    
    // 在 按钮 点击事件 中进行修改, 界面也不会更新
    const add = ()=>{
        counter.count.value++
    
        counter.$patch({
            count: counter.count + 1
        })
    
        // counter.increment()
        console.log(counter.count)
    }
    
    // 注意, 顶层作用域中,修改数据,界面之所以会受影响并进行改变, 
    // 是因为, 模板 template 作用域 , 和 setup 函数作用域是一样的, 
    // 本人认为 和 pinia 并没有什么关系
    
    
    
    1. 如果 想让 数据变成响应式的, 则可将 /stores/countes.js 文件进行如下方式进行数据的定义
    import { defineStore } from "pinia";
    import { ref } from "vue";
    
    export const useCounterStore = defineStore("counter" ,()=>{
        const count = ref(6);
    
        function increment(){
            count.value++
        }
    
        return {
            count,
            increment
        }
    })
    

    确实, 按照如上 方式进行 count 数据的定义, 确实变成响应式数据了, 但这跟pinia有啥关系, 这不是用了vue3的ref么, 说的不好听点, 单靠vue3的ref , 我不用pinia, 也可以啊, 为什么要用pinia呢

    1. 所以, 最终我的代码变成了这样
    // /stores/counter.js
    // 老子不用 pinia 了, 自己封装数据挺好的
    import { ref } from "vue";
    
    export const myStore = ()=>{
        const count = ref(6);
    
        return {
            count,
        }
    }
    
    

    在组件中使用

    import {myStore} from "@/stores/counter"
    var data = myStore()
    data.count.value++
    

    一切都是那么的香, 跟 pinia 没有任何关系

    相关文章

      网友评论

        本文标题:vue3 状态管理 之 Pinia --- 三分钟放弃

        本文链接:https://www.haomeiwen.com/subject/kcqpartx.html