Pinia的两种写法
Pinia支持两种写法,跟Vue3一样,既支持选项式(options)写法,也支持组合式(setup)写法
举个例子
选项式写法
export const useCounterStore = defineStore('main', {
state: () => ({
count: 0,
}),
getters: {
double() {
return this.count * 2
}
},
actions: {
increment() {
this.count++
}
},
})
组合式写法
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('main', () => {
const count = ref(0)
const double = computed(() => {
return count.value * 2
})
function increment() {
count.value++
}
return { count, double, increment }
})
如何继承BaseStore
如果你有一个BaseStore里面有一些通用的方法, 想在当前的xxxStore中继承BaseStore, 可以通过下面这种方法实现
使用场景:
例如在每个Table页面都有: [获取Table数据 / 删除 / 提交 / 审核...]这些操作,这些操作用的Store方法基本上都是一样的,这时候就可以把 [获取Table数据 / 删除 / 提交 / 审核...] 放到BaseStore中, 在当前的Store中导入
BaseStore
/**
* 操作: index列表数据/编辑页数据/新增或编辑/批量新增/删除/审核/禁用/提交
* @returns
*/
export const BaseStore = (...参数) => {
return {
/** 获取index视图列表数据 */
GetViewTable(data) {
...
},
/** 获取编辑页数据 */
GetDetails(id) {
...
},
/** 新增或编辑操作 */
AddOrUpdate(jsonData) {
...
},
/** 批量新增 */
BatchAdd(jsonData) {
...
},
/** 删除 */
Delete(ids) {
...
},
/** 审核/反审核 */
Examine(ids, state) {
...
},
/** 禁用/启用 */
Prohibit(ids, state) {
...
},
/** 提交/撤回 */
Submit(ids, state) {
...
}
}
}
选项式写法
import { BaseStore } from '@/store/modules/BaseStore'
export const useCounterStore = defineStore('main', {
state: () => ({
count: 0,
}),
getters: {
double() {
return this.count * 2
}
},
actions: {
...BaseStore(...参数),
increment() {
this.count++
}
},
})
组合式写法
import { ref, computed } from 'vue'
import { BaseStore } from '@/store/modules/BaseStore'
export const useCounterStore = defineStore('main', () => {
const count = ref(0)
const double = computed(() => {
return count.value * 2
})
function increment() {
count.value++
}
return {
...BaseStore(...参数),
count,
double,
increment
}
})