通常我们在.vue文件中,使用组合式api采用以下两种写法:
- 第一种使用
setup()函数中声明并返回它们:
<script>
import { ref } from 'vue'
export default {
// `setup` 是一个特殊的钩子,专门用于组合式 API。
setup() {
const count = ref(0)
// 将 ref 暴露给模板
return {
count
}
}
}
</script>
- 第二种在script标签中使用setup:
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
由此可以看出来使用第二种写法比较简洁,也更加推荐第二种写法
那么在pinia中怎么写呢?
pinia官网上同样有两种写法
第一种的写法: pinia.vuejs.org/zh/core-con…
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
第二种写法: pinia.vuejs.org/zh/cookbook…
export const useCartStore = defineStore('cart', () => {
const list = ref([])
function purchase() {
return apiPurchase(user.id, this.list)
}
return { list, purchase }
})
我通常使用第二种写法,看起来更简洁干净。