本文主要是介绍Vue:状态管理pinia,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装
npm install pinia
在 main.js 中注册
// main.jsimport { createApp } from 'vue'
import { createPinia } from "pinia";
import App from './app.vue'const app = createApp(App)
const pinia = createPinia();
app.use(pinia).mount('#app')
创建 store
// stores/counter.jsimport { defineStore } from "pinia";export const useCounterStore = defineStore("counter", {state: () => ({count: 0,}),getters: { // 类似计算属性,基于store中的状态进行动态计算。当它们所依赖的state发生变化时,getters会自动更新其返回值。double: (state) => { return state.count * 2;},},actions: {increase() {this.count++;},},
});
使用 store
<!-- Counter.vue --><script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'const counter = useCounterStore();
const { count, double } = storeToRefs(counter); // 将store中的结构数据转为响应式的ref对象
</script><template><button @click="counter.increase">{{ count }} - {{ double }}</button>
<template>
这篇关于Vue:状态管理pinia的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!