Pinia的Setup Store写法

218 阅读1分钟

Setup Store写法。在defineStore()中传递两个参数,第一个参数对应的是id第二个参数是一个回调函数, 这个函数的用法与setup()类似。具体写法如下:

export const useUserStore = defineStore('userStore', () => {

  // 这里对应的是state: () => ({ userInfo: {} }),
  const userInfo = reactive({})
  
  // 这里对应的就是 action: {} 里的函数
  function getUserInfo() {
    return new Promise((resolve, reject) => { 
       axios.get('user').then((res) => { 
          userInfo = res.data
       })
    })
  }

  // 最后暴露出去
  return { count, increment }
})

以上这种写法相比 Option Store书写更加的灵活 ,因为你可以在一个 store内创建侦听器,并自由地使用任何组合式函数。

本文由mdnice多平台发布