计算属性内的Pinia未定义状态



我尝试将Pinia与组合Api一起使用,并定义类似商店的:

export const useOfficeStore = defineStore("office", () => {
const rooms = ref(new Map());
rooms.value.set("first", {
id: "first",
width: 20,
height: 20,
top: 0,
left: 0,
pers: null,
});
const freeRooms = computed(function (state) {
console.log("Invoked free rooms", state);
return this.rooms;
});
return {
rooms,
freeRooms,
};
});

在我的组件中,我导入的状态如下:

import { useOfficeStore } from "@/stores/counter";
const store = useOfficeStore();
function mark() {
console.log("Free", store.freeRooms);
}

当我调用计算属性时,我会面对这些日志:

Invoked free rooms undefined
Free undefined

我做错了什么?

由于混合了两种语法,因此您将无法定义。以下是来自pinia文档的示例:

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

在组合API的情况下,不能使用访问状态属性,并且计算函数不再将state作为参数。因此,在您的情况下,函数应该如下所示:

const freeRooms = computed(function () {
console.log("Invoked free rooms");
return rooms.value;
});

最新更新