Pinia + 组合式写法 + 选项式写法

选项式:

1.定义Store

import { defineStore } from 'pinia'

// option api  选项式
export const useAlterStore = defineStore('alter', {
     state: () => {
          return {
               num: 1
          }
     },

     getters: { // 可以看做是计算属性
          doubleCount: (state) => state.num * 2
     },

     actions: {
        // 同步方法
         add() {
              this.num++
         },

         // 异步方法
        async asyncAdd() {
              await new Promise((resolve) => {
                   setTimeout(resolve, 1000)
              })
              this.add()
         }
    }
})
  1. 使用Store
    //引入store
    import { useAlterStore } from '../store/useAlterStore.js';   
    import { storeToRefs } from 'pinia'
    
    const store = useAlterStore(); // 拿到仓库
    const { num, doubleCount } = storeToRefs(store); // 把仓库中的数据变成响应式
    const { add, asyncAdd } = store // 拿到仓库方法

组合式:

1.定义Store

import { defineStore } from 'pinia'
import { reactive, computed } from 'vue'

export const useListStore = defineStore('list', () => {
	 const list = reactive({
        inputValue: '1',
        conter: 100,
        items: [
            {
                txt: '学习pinia',
                isCompleted: true
            }
        ]
    })
    const doubleCounter = computed(() => list.conter * 2)
 	const deleteItem = (index) => {
        list.items.splice(index, 1)
    }
    return {
		list,
		doubleCounter,
		deleteItem
	}

})
  1. 使用Store
    //引入store
    import { useAlterStore } from '../store/useAlterStore.js';   
    import { storeToRefs } from 'pinia'
    
    // 获取仓库
    const store = useListStore()
    const { list, doubleCounter } = storeToRefs(store) // 把仓库中的数据变成响应式
    const { deleteItem } = store // 拿到仓库方法

重置state

const store = useStore()
store.$reset()

注意:pinia使用setup函数创建store $reset()失效
在这里插入图片描述

可以使用options创建或者重写一个$reset方法

变更state

 store.$patch({
    num: inputVal.value
  })

全局挂载

main.js

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import './index.css'

const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值