英文:
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 '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);
}
}
答案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("openBag");
// 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:
<div x-data="setData" @open_bag.window.camel="showDrawer = true; drawerTab = 'bag'">
...
</div>
If the component receives the openBag
custom event, then it will mutate some of its properties.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论