Pinia是什么?
yarn add pinia -s
yarn config set ignore-engines true
- import { createApp } from 'vue'
- import App from './App.vue'
- import router from './router/index'
- import {createPinia} from 'pinia'
- const pinia = createPinia();//实例化pinia
- createApp(App).use(router).use(pinia).mount('#app')
- import { defineStore } from 'pinia'
- export const mainStore = defineStore('main',{
- state(){
- return {
- title:'itlove',
- count:1,
- }
- },
- getters:{
- changeCount(){
- return this.count+10
- }
- },
- actions:{
- addCount(){
- }
- }
- })
-
-
{{store.title}}
-
- import {ref,reactive} from 'vue'
- import {mainStore} from '@/store/index' //导入状态仓库
- const store = mainStore(); //实例化仓库
或者
-
-
{{title}}
-
- import {ref,reactive} from 'vue'
- import {mainStore} from '@/store/index' //导入状态仓库
- const {title} = mainStore(); //实例化仓库
-
-
{{store.title}}
-
数据:{{store.count}}
-
-
- import {ref,reactive} from 'vue'
- import {mainStore} from '@/store/index' //导入状态仓库
- import { storeToRefs } from "pinia";
- const store = mainStore(); //实例化仓库
- // 解构并使数据具有响应式
- const {count} = storeToRefs(store);
- function handleClick() {
- count.value++;
- }
- actions:{
- //actions 异步请求
- async login(user, password) {
- const userData = await apiLogin(user, password);
-
- this.$patch({
- name: user,
- ...userData,
- })
- }
- }
- import {createPinia} from 'pinia'
- import piniaPluginPersist from 'pinia-plugin-persist'
- const pinia = createPinia();
- pinia.use(piniaPluginPersist);
- createApp(App).use(router).use(pinia).mount('#app')
- persist: {
- enabled: true, //开启
- strategies:[
- {
- key: 'store',
- storage: sessionStorage,
- paths:['count']
- }
- ]
- }
以下为实战
应用
后续高级 提升
- import {createPinia} from 'pinia'
- import piniaPluginPersist from 'pinia-plugin-persist'
- const pinia = createPinia();
- pinia.use(piniaPluginPersist);
- createApp(App).use(router).use(pinia).mount('#app')
- persist: {
- enabled: true, //开启
- strategies:[
- {
- key: 'store',
- storage: sessionStorage,
- paths:['count']
- }
- ]
- }