Vue.js 3.0 之 Pinia 基础知识

系列文章目录

提示:阅读本章之前,请先阅读目录



前言


安装

npm install pinia

引入

// Vue 3.0 写法
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

const store = createPinia()
const app = createApp(App)
app.use(store)
app.mount('#app')

创建

import { defineStore } from 'pinia'


const Login = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            return resolve({
                name: "大狼狗"
            })
        }, 2000)
    })
}

export const useTestStore  = defineStore("Test", {
    state: () => {
        return {
            name: "xiaofeng",
            age: 9999
        }
    },
    getters: {
        testName () {
            return `hello${this.name}`
        }
    },
    actions: {
        setName() {
            this.name = "0000000000"
        },
        async setSyncName () {
           const res = await Login()
           this.$state = res
        }
    }
})

使用方法

import { useTestStore } from './store/index.ts'
import { storeToRefs } from 'pinia'
export default {
  name: 'App',
  setup() {
    const store = useTestStore()
    store.name = "kekeke"
    store.$patch({
      name: "999999"
    })
    store.$patch((state) => {
      state.name = "8888888"
    })
    store.$state = {
      name: "55555555"
    }
    store.setName()

    const { name } = storeToRefs(store)
    const change = () => {
      store.setSyncName()
    }
    return{
      store,
      name,
      change
    }

  }
}

监听 subscribe

import { useTestStore } from './store/index.ts'
export default {
  name: 'App',
  setup() {
    const store = useTestStore()

    store.$subscribe((args, state) => {
      console.log("我监听到了", args)
      console.log("我监听到了", state)
    })

    const change = () => {
      store.setName()
    }
    
    return{
      store,
      change
    }

  }
}

在这里插入图片描述

onActions 捕获

const store = useTestStore()

store.$onAction((args) => {
  console.log("Actions,捕获", args)
})

在这里插入图片描述

持久化

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值