vue3使用pinia

vue3使用pinia

介绍

pinia的介绍官网都有的,可查阅中文版,官网:https://pinia.web3doc.top

安装

yarn add pinia
or
npm i pinia

创建store

// store/index.ts
import { defineStore } from 'pinia'
// defineStore(key,options) 必须传递一个唯一key作为标识
export const useCounterStore = defineStore('counterStore', {
  state: () => ({
    counter: 0
  }),
  actions: {
    // 方法 可以是异步 async addCounter(){}
    // 在这里也可以访问其他的store
    addCounter () {
      this.counter++
    }
  },
  getters: {
    doubleCounter (state):number {
      // 可以使用this
      // return this.counter * 2
      // 在这里也可以访问其他的store
      return state.counter * 2
    }
  }
})

使用

// main.ts
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
createApp(App)
  .use(createPinia())
  .mount('#app')

在组件中使用store

<template>
  <h1>HelloWorld</h1>
  <h3>counter:{{ counter }}</h3>
  <h3>doubleCounter:{{ doubleCounter }}</h3>
  <button @click="addCounter">
    counter++
  </button><br>
  <button @click="replaceStore">
    替换state状态值
  </button>
</template>

<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '../store'
const counterStore = useCounterStore()
// 第一次改变store状态 $path对象形式
// const addCounter = () => {
//   counterStore.$patch({
//     counter: counterStore.counter + 1
//   })
// }
// 第二种修改store状态 $path 传递回调函数 第一个参数就是state
// const addCounter = () => {
//   counterStore.$patch((store) => {
//     store.counter++
//   })
// }
// 第三种修改store状态 直接通过store修改
// const addCounter = () => {
//   counterStore.counter++
// }
// 第四种修改store状态
const addCounter = () => {
  counterStore.addCounter()
}

// 访问state的状态两个方法
// !不能这样使用 因为丢掉了响应式
// const { counter, doubleCounter } = counterStore

// 一使用pinia自带的storeToRefs
const { counter, doubleCounter } = storeToRefs(counterStore)

// 二使用vue的computer 从store中读取
// const counter = computed(() => counterStore.counter)
// const doubleCounter = computed(() => counterStore.doubleCounter)


// 替换状态已有的属性值 相当于重新赋值而已
const replaceStore = () => {
  counterStore.$state = { counter: 20 }
}
</script>

以上只是pinia的基本使用,具体内容还是参考官方为准!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值