You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sveltestrap Modal组件中Svelte属性未按预期更新问题排查

问题分析与解决方案

你的问题出在Sveltestrap Modal组件的响应式更新机制上:初始时Modal就处于打开状态(isOpen={true}),其内部内容在组件挂载时一次性渲染完成,后续currentPollType更新后,由于Bootstrap模态框的DOM处理逻辑,Svelte的响应式追踪无法触发Modal内容的重新渲染,导致页面始终显示初始的null。

解决方法1:用{#key}强制触发内容更新

Svelte的{#key}块可以监听指定变量的变化,一旦变量更新就会重新渲染块内的所有内容,完美解决这个问题:

<script>
import {Modal, ModalBody} from 'sveltestrap';

let currentPollType = null;

const myPoll = {
    type: 1,
    // ...
};

const onClickBroadcast = function(e, poll) {
    console.log(poll.type);
    currentPollType = poll.type;
    console.log('currentPollType', currentPollType);
};
</script>

<button
    type="button"
    class="btn btn-primary btn-sm"
    on:click={(e) => onClickBroadcast(e, myPoll)}>
    Broadcast
</button>

<Modal isOpen={true} size="lg">
    {#key currentPollType}
    <ModalBody>
        Poll type: {currentPollType}
    </ModalBody>
    {/key}
</Modal>

解决方法2:修改Modal的触发逻辑(更符合常规用法)

如果Modal不需要一直显示,而是点击按钮后再打开,建议将isOpen绑定到响应式变量,点击时同时更新currentPollType和打开Modal:

<script>
import {Modal, ModalBody} from 'sveltestrap';

let currentPollType = null;
let isModalOpen = false;

const myPoll = {
    type: 1,
    // ...
};

const onClickBroadcast = function(e, poll) {
    currentPollType = poll.type;
    isModalOpen = true;
};
</script>

<button
    type="button"
    class="btn btn-primary btn-sm"
    on:click={(e) => onClickBroadcast(e, myPoll)}>
    Broadcast
</button>

<Modal isOpen={isModalOpen} size="lg">
    <ModalBody>
        Poll type: {currentPollType}
    </ModalBody>
</Modal>

这种方式下,Modal会在点击按钮后才渲染内容,此时currentPollType已经完成赋值,自然能正确显示;后续如果currentPollType发生变化,内容也会自动响应更新。

内容的提问来源于stack exchange,提问作者nnyby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:20:37