dwe*_*ird 3 javascript node.js svelte
我试图在 if else 块之间放置一个函数。下面是我想象的。:
<script>
let condition=false
function function_here(event){
if(event){
condition = true;
}else if(!event){
condition = false;
}else{
condition = !condition;
}
</script>
{#each post as posts}
{#if posts.object1==="match" }
<p>HTML HERE</p>
{function_here(true)}
{/if}
{/each}
{#if condition}
<button>type1</button>
{:else}
<button>type2</button>
{/if}
Run Code Online (Sandbox Code Playgroud)
如果仅在循环发布结果期间,如果发现 posts.object1 匹配,我需要更改变量“条件”的状态
但是,此示例返回结果“未定义”。
我如何在 if 块之间放置函数?
在 Svelte 中,像这样调用模板内部的函数被认为是不好的做法,该代码属于组件的脚本部分。这个问题的最佳方法是一个反应变量,这样它也会随着posts变化而变化:
$: condition = posts.... // something based on posts
Run Code Online (Sandbox Code Playgroud)
虽然实际结果取决于您,但您在答案中提供的代码似乎与实际代码非常简化。
小智 1
您正在尝试以 JSX 想要的方式来解决这个问题。为什么不将该逻辑抽象到纯 JS 中<script>?
<script>
let condition = false
function function_here(event) {
if (event) {
condition = true;
} else if (!event) {
condition = false;
} else {
condition = !condition;
}
}
for (post in posts) {
if (post.object1 === 'match') {
function_here(true)
}
}
</script>
{#each post as posts}
{#if post.object1 === "match" }
<p>HTML HERE</p>
{/if}
{/each}
{#if condition}
<button>type1</button>
{:else}
<button>type2</button>
{/if}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
898 次 |
| 最近记录: |