json vue 3在Component @click上将prop对象传递到LocalStorage中

enyaitl3  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(114)

我试图通过一个 prop (派系)从一个组件(派系选项)上的@click事件的选项。

FactionOption.vue

<script setup>
import { selectFaction } from '../../composables/selectFaction';

defineProps({
    faction: {
        type: Object,
        required: true
    }
})

function setFaction(f) {
    selectFaction(f)
}

</script>

<template>
    <div class="option">
        <p class="option__text">{{ faction.name }} - {{ faction.title }}</p>
        <button class="button button--link" key="select" @click="setFaction(faction)">Select</button>
    </div>
</template>

字符串
上面的代码将Object传递给selectedFaction.ts:

selectFaction.ts

import { toRaw } from "vue";
import { selectedFaction } from "./useFactions";

export function selectFaction(faction) {
    const theFaction = selectedFaction();
    const rawObject = toRaw(faction);
    console.log(rawObject)
    console.log(theFaction.value)

    return () => {
        theFaction.value = [rawObject];
    };
}


控制台准确地将对象转换为来自代理的原始值。

useFactions.ts

import { Faction } from "../models/Faction";
import { createGlobalState, useLocalStorage } from "@vueuse/core";

export const selectedFaction = createGlobalState(() => {
    return useLocalStorage<Faction[]>("@battleline/selectedFaction", []);
});


但是,当单击该按钮时,会向LocalStorage中插入一个空数组,用于“@battleline/selectedFaction”。
我是Vue 3的新手,为什么返回一个空数组?TYIA

dba5bblo

dba5bblo1#

return () => {
  theFaction.value = [rawObject];
};

字符串
这意味着您返回的函数将只在调用该函数时执行内部语句。
您的组件需要将此返回值分配给某个const,以便它可以调用它:

const returnedFunction = selectFaction(f)
returnedFunction()


或者只是

selectFaction(f)()


或者,您不需要从selectFaction composable返回任何内容。如果你只想设置你的全局状态/ localStorage,这将完成这项工作,并且FactionOption.vue不需要任何更改:

export function selectFaction(faction) {
  const theFaction = selectedFaction();
  const rawObject = toRaw(faction);
  theFaction.value = [rawObject]
}

相关问题