微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 JavaScript 中使用 AlpineJS $persist 而不是 HTML

如何解决在 JavaScript 中使用 AlpineJS $persist 而不是 HTML

通过 this article 我了解到您也可以通过 JS 访问这些魔法变量(例如在 HTML <div x-ref="navbarCollapse">...</div> 和 JS this.$refs.navbarCollapse 中)。

我想知道这是否也适用于 Persist plugin。目标是存储用户是否接受 Cookie Banner 的布尔值。

所以我尝试设置变量,就好像它放在 x-data 中一样,它看起来像:

export default () => ({
    open: this.$persist(false),});

但这会抛出:

module.esm.js:1656 Alpine Expression Error: Illegal invocation

Expression: "open"

接下来我尝试放入我的 init() 函数(这是 async,因为我在其中使用了 GraphQL)

export default () => ({
    open: false,async init() {
        this.open = this.$persist(false);
        ...
    }
});

然后什么也没发生。

这里的更多上下文是我目前正在使用的示例,其中包含我自己的用于读取/写入本地存储的函数

import client from './graphql';
import {
    gql,} from '@apollo/client/core';
import {
    storageGet,storageHas,storageSet,} from './local-storage';

const COOKIE_CONSENT_NAME = 'cookieConsentAccepted';

export default () => ({
    open: false,enabled: false,async init() {
        // Get all relevant information from the API
        const response = await client.query(
            {
                query: gql`
                    {
                        globalSets(handle: "globalsCookieBanner") {
                            ... on globalsCookieBanner_GlobalSet {
                                cookieBannerStatus
                            }
                        }
                    }
                `,});
        const data = response.data.globalSets[0];
        this.enabled = data.cookieBannerStatus;

        // Check whether to open cookie banner
        if (this.enabled && (!storageHas(COOKIE_CONSENT_NAME) || (storageHas(COOKIE_CONSENT_NAME) && storageGet(COOKIE_CONSENT_NAME === false)))) {
            this.open = true;
        }
    },toggle() {
        this.open = !this.open;
        storageSet(COOKIE_CONSENT_NAME,!this.open);
    },});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。