searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

pinia编写store的两种写法

2024-04-07 09:27:52
4
0

选项式API写法

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

组合式API写法

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

二者的对比

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 action

使用

<script setup>
import { useCounterStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
</script>

 

0条评论
作者已关闭评论
c****i
1文章数
0粉丝数
c****i
1 文章 | 0 粉丝
c****i
1文章数
0粉丝数
c****i
1 文章 | 0 粉丝
原创

pinia编写store的两种写法

2024-04-07 09:27:52
4
0

选项式API写法

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

组合式API写法

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

二者的对比

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 action

使用

<script setup>
import { useCounterStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
</script>

 

文章来自个人专栏
文章 | 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0