pinia官网:https://pinia.vuejs.org/
pinia菠萝挺不错,简单又灵活。
1.安装:yarn add pinia 或者 npm install pinia,全局加 --location=global
2.注册使用 main.js
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',{...});
更多参考官网
分类:
Vue.js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2021-08-24 SpringMVC中@ControllerAdvice/@RestControllerAdvice注解,全局异常处理