Alpine JS从js函数内更改数据。

huangapple go评论73阅读模式
英文:

Alpine JS change data from within a js function

问题

我正在尝试在加载产品到购物袋后,从较大的JavaScript文件中调用函数openBag();

在这段代码中,changeData 一直返回为未定义。这是否是正确的方法?我是否有错,还是应该以不同的方式处理这个问题?

import Alpine from 'alpinejs'
window.Alpine = Alpine

window.addEventListener('alpine:init', () => {
	Alpine.data('setData', () => ({
		showDrawer:false, drawerTab:'', showNav:false, showBack:false, showMenu:false, showFilters:false, isMobile:(window.innerWidth < 480) ? true : false
	}))
})

Alpine.start()

window.openBag = function() {
	const changeData = Alpine.data('setData');
	if (changeData) {
		changeData.showDrawer = true,
		changeData.drawerTab = 'bag'
	} else {
		console.log(changeData);
	}
}
英文:

I'm trying to call a function openBag(); from a larger js file once it has finished loading a product into the bag.

I have this code where changeData keeps coming back as undefined.

Is this the correct approach? Do I have something wrong, or should I approach this in a different way?

import Alpine from &#39;alpinejs&#39;
window.Alpine = Alpine

window.addEventListener(&#39;alpine:init&#39;, () =&gt; {
	Alpine.data(&#39;setData&#39;, () =&gt; ({
		showDrawer:false, drawerTab:&#39;&#39;, showNav:false, showBack:false, showMenu:false, showFilters:false, isMobile:(window.innerWidth &lt; 480) ? true : false
	}))
})

Alpine.start()

window.openBag = function() {
	const changeData = Alpine.data(&#39;setData&#39;);
	if (changeData) {
		changeData.showDrawer = true,
		changeData.drawerTab = &#39;bag&#39;
	} else {
		console.log(changeData);
	}
}

答案1

得分: 0

使用 Alpine.data() 可以定义一个组件,它不用于访问组件的属性。您正在寻找的是组件上的事件监听器,该监听器可以在其他 JavaScript 函数中触发 openBag 事件,例如:

const openBagEvent = new Event("openBag");

// 在某个元素上触发事件(可以是 body)
element.dispatchEvent(openBagEvent);

在 Alpine.js 组件中,我们可以使用 x-on 快捷方式创建一个事件监听器:

<div x-data="setData" @open_bag.window.camel="showDrawer = true; drawerTab = 'bag'">
...
</div>

如果组件接收到 openBag 自定义事件,则它将改变其一些属性。

英文:

With Alpine.data() you can define a component, it's not for accessing the component's properties. What you are looking for is an event listener on the component that can act if the openBag event is dispatched form the other JS function, like:

const openBagEvent = new Event(&quot;openBag&quot;);

// Dispatch the event on some element (can be the body)
element.dispatchEvent(openBagEvent);

And at the Alpine.js component we create an event listener with x-on shortcut:

&lt;div x-data=&quot;setData&quot; @open_bag.window.camel=&quot;showDrawer = true; drawerTab = &#39;bag&#39;&quot;&gt;
...
&lt;/div&gt;

If the component receives the openBag custom event, then it will mutate some of its properties.

huangapple
  • 本文由 发表于 2023年5月17日 07:47:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76267739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定