posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
pinia官网:https://pinia.vuejs.org/
pinia菠萝挺不错,简单又灵活。
1.安装:yarn add pinia 或者 npm install pinia,全局加 --location=global
2.注册使用 main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

1
2
3
4
5
6
7
8
9
10
11
12
13
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}}

1
2
3
4
5
6
7
8
9
10
<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',{...});
更多参考官网

posted on   邢帅杰  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2021-08-24 SpringMVC中@ControllerAdvice/@RestControllerAdvice注解,全局异常处理
点击右上角即可分享
微信分享提示