Svelte in markdown
This feature allows you to write <style>, #if, <script>, <script module> #each, #await, #snippet, @render @html, @const, <svelte:xxx>' in .md files
Basic
这里是一个使用了 #if, #each, #await, @html, @const 的基础示例
- 1: foo
- 2: bar
- 3: zoo
失败
加载中
使用 @html 渲染的内容
<script>
let count = $state(0)
const items = ['foo', 'bar', 'zoo']
let boolVal = $state(false)
const promisePass = () => new Promise(resolve => {
setTimeout(() => {
resolve('Promise 通过!')
}, 2000)
})
const promiseFail = () => new Promise((_, reject) => {
setTimeout(() => {
reject('Promise 未通过!')
}, 2000)
})
let promise = $derived(boolVal ? promisePass() : promiseFail())
</script>
<ul>
{#each items as item, i}
{@const str = `${i + 1}: ${item}`}
<li>
{str}
</li>
{/each}
</ul>
<button onclick="{() => boolVal = !boolVal}">
切换
</button>
{#if boolVal}
<h3 class="text-green">
通过
</h3>
{:else}
<h3 class="text-red">
失败
</h3>
{/if}
{#await promise}
<h3 class="text-orange">
加载中
</h3>
{:then res}
<h3 class="text-green">
{res}
</h3>
{:catch err}
<h3 class="text-red">
{err}
</h3>
{/await}
{@html "<h1>使用 @html 渲染的内容</h1>"} md
点击展开/折叠代码
语法限制
始终使用 "" 包裹语法.
-
+
<script>
let count = $state(0)
</script>
<button onclick={() => count++}></button>
<button onclick="{() => count++}"></button> md
或者也可以使用一个空的 div 包裹
-
+
+
+
<script>
let count = $state(0)
</script>
<button onclick={() => count++}></button>
<div>
<button onclick={() => count++}></button>
</div> md
一个计数器示例
一个计数器