外贸服装商城网站建设,宽屏网站模板,办营业执照要多少钱,宣传广告制作效果图前言#xff1a; 好用的状态管理器#xff0c;vue3中出来的pinia#xff0c;相比较vuex来说#xff0c;更加轻便#xff0c;使用也更方便。 官方文档#xff1a;点我
github地址#xff1a;点我
pinia与vuex相比较优点#xff1a; pinia 是轻量级状态管理工具#x…前言 好用的状态管理器vue3中出来的pinia相比较vuex来说更加轻便使用也更方便。 官方文档点我
github地址点我
pinia与vuex相比较优点 pinia 是轻量级状态管理工具大小只有1KB.pinia 模块化设计方便拆分。pinia 没有 mutations直接在 actions 中操作 statepinia 支持多个 store。 使用步骤
1、安装 npm/cnpm/pnpm/yarn 都可以装上下面插件
pinia
2、main.js中配置
const pinia createPinia();const app createApp(App);
app.use(pinia);
3、创建stores 文件夹
1官方案例1
新建一个counter.ts
import { defineStore } from piniaexport const useCounterStore defineStore(counter, {state: () {return { count: 0 }},// 也可以定义为// state: () ({ count: 0 })actions: {increment() {this.count},},
})
调用的vue
import { useCounterStore } from /stores/counterexport default {setup() {const counter useCounterStore()counter.count// 带自动补全 ✨counter.$patch({ count: counter.count 1 })// 或使用 action 代替counter.increment()},
}
2官方案例2
定义ts
export const useStore defineStore(main, {state: () ({counter: 1,}),actions: {increment() {this.counter}},getters: {// 类型是自动推断的因为我们没有使用 thisdoubleCount: (state) state.counter * 2,/*** 返回计数器值乘以二加一。** returns {number} 返回类型必须明确设置*/doubleCountPlusOne(): number {// 自动完成 ✨return this.doubleCount 1},},})
页面使用
templatepDouble count is {{ store.doubleCount }}/p
/templatescript setupconst store useStore()const a store.counterstore.increment()
/script
3个人使用
新建 useChatStore.ts
import {ref} from vue;
import {acceptHMRUpdate, defineStore} from pinia;export const useChatStore defineStore(chat, () {// 定义变量const conversations ref([]);// 定义方法const getConversations async (page 1, search , type ) {//可以做任何操作};return {conversations ,getConversations };})if (import.meta.hot) {import.meta.hot.accept(acceptHMRUpdate(useChatStore, import.meta.hot));
}
页面调用
template{{chatStore.conversations }} //拿到数据了script langts setupimport { useChatStore } from //stores/useChatStore;const chatStore useChatStore();//调用定义的方法chatStore.getConversations()
额外的插件解决刷新数据丢失问题 pinia-plugin-persist 1、安装 npm/cnpm/pnpm/yarn 都可以装上下面插件
pinia-plugin-persist
2、main.js中配置
import { createPinia} from pinia
import piniaPluginPersist from pinia-plugin-persist //
const store createPinia()
store.use(piniaPluginPersist) //
3、相应的ts文件中
import { defineStore } from pinia;
export const useStore defineStore({state: () ({active: 111,}),getters: {},// 开启数据缓存 若 需要state 中的变量页面刷新数据缓存 需要调用 actions 中的方法actions: {setActive( active ){this.active active},},persist: {enabled: true, // 开启数据缓存 }
});
4、页面上
import { useActiveStore } from //stores/useChatStore // 引用 pinia 数据
const store useActiveStore() // 定义 store 接收
store.setActive(222)
到此结束