问题描述
通过 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 (将#修改为@)