【问题标题】:How can I pass a value to init methods on import?如何在导入时将值传递给 init 方法?
【发布时间】:2021-10-29 23:35:01
【问题描述】:

假设我有这样的组件:

'use strict';

export default () => ({
    selected: false,
    init(selectedIndex: -1)
    {

    }

});

我像这样导入它(使用 AlpineJS 3):

import Alpine from 'alpinejs'

window.Alpine = Alpine

window.Components = {};

import Tab from "./components/Tab";
window.Components.Tab = Tab;

Alpine.start();

我现在如何将值传递给init 方法?

当我有:

<div x-data="Components.Tab(0)">...</div>

值显然没有传递给init方法。

虽然文档中有关于如何register component from a bundle 的信息和关于如何pass initial parameters 的信息,但没有关于如何将初始参数传递给从捆绑包中注册的组件的信息

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    正如您在the documentation of the init function 中看到的:

    如果您的组件包含init() 方法

    您不能向init() 方法添加参数(注意两个括号表示没有参数)。

    必须将参数添加到组件本身。所以你的组件定义应该是:

    'use strict';
    
    export default (initialSelected = -1) => ({
        selected: initialSelected,
        init()
        {
    
        }
    
    });
    

    顺便说一句,我注意到您的 selected 字段是布尔值,而您的 selectedIndex 参数是数字。在我上面更正的代码中,我只是对两者都使用了数字。

    另外,你已经在你的代码中使用了这个:

    window.Components.Tab = Tab;
    

    但是the documentation you have linked to 说您需要使用Alpine.data('Tab', Tab) 从捆绑包中注册。

    【讨论】:

    • 谢谢。我用它来添加额外的“属性”,然后在init 方法中我使用它们来设置其他“真实”属性
    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2011-12-07
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多