繁体   English   中英

我需要在 Alpine.js 组件的初始化处触发一个“更改”事件

[英]I need to fire a “change” event at the init of an Alpine.js component

我是 Alpine.js 的新手,我正在为这个简单的任务而苦苦挣扎。 我在一个表格中有两个 select。 我用 JS 脚本填充第一个,然后当用户 select 一个值时,脚本填充第二个 select。

我的问题是,当用户在提交后返回同一个表单时,我需要在第一个 select 上触发一个更改事件,以使第二个为我必须 select 的值做好准备。

这是我的代码。 我明白了。$refs.select_one.change 不是 function 谢谢你的帮助

<div x-data="load_form()" x-init="init">

    <form>
        <select name="first" x-ref="select_one" x-model="first_select"></select>
        <select name="second" x-model="second_select"></select>
    </form>

</div>

function load_form() {
    return {
        first_select: "",
        second_select: "",            
        init() {
            script_that_populate_selects("#select1", "#select2");
            // set the first
            this.first_select = "value1";
            // this should fire the change event
            this.$nextTick(() => this.$refs.select_one.change());
            // wait before set the second value
            setTimeout(()=> {
                this.second_select = "value2";
            }, 1500);
        }
    }
}

我明白我的错这是触发更改事件的正确指令

this.$nextTick(() => this.$refs.select_one.dispatchEvent(new Event("change"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM