$host
当将组件编译为自定义元素时,$host
符文提供了对宿主元素的访问,使您能够(例如)触发自定义事件(demo):
Stepper
<svelte:options customElement="my-stepper" />
<script>
function dispatch(type) {
$host().dispatchEvent(new CustomEvent(type));
}
</script>
<button onclick={() => dispatch('decrement')}>减少</button>
<button onclick={() => dispatch('increment')}>增加</button>
<svelte:options customElement="my-stepper" />
<script lang="ts">
function dispatch(type) {
$host().dispatchEvent(new CustomEvent(type));
}
</script>
<button onclick={() => dispatch('decrement')}>减少</button>
<button onclick={() => dispatch('increment')}>增加</button>
App
<script>
import './Stepper.svelte';
let count = $state(0);
</script>
<my-stepper
ondecrement={() => count -= 1}
onincrement={() => count += 1}
></my-stepper>
<p>计数: {count}</p>
<script lang="ts">
import './Stepper.svelte';
let count = $state(0);
</script>
<my-stepper
ondecrement={() => count -= 1}
onincrement={() => count += 1}
></my-stepper>
<p>计数: {count}</p>