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

诗远

关注

阅读 48

2024-06-28

选项式:

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()

变更state

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

精彩评论(0)

0 0 举报