面试题答案
一键面试- 创建子组件
Child.svelte
:<script> let count = 0; function increment() { count++; // 使用 `createEventDispatcher` 创建事件分发器 const dispatch = createEventDispatcher(); // 触发自定义事件 `count-changed`,并传递数据 dispatch('count-changed', { newCount: count }); } </script> <button on:click={increment}>Increment in Child</button>
- 创建父组件
Parent.svelte
:<script> import Child from './Child.svelte'; function handleCountChange(event) { console.log('Count changed in child, new value:', event.detail.newCount); } </script> <Child on:count-changed={handleCountChange} />
在上述代码中:
- 在子组件
Child.svelte
中,使用createEventDispatcher
创建事件分发器,通过dispatch
方法触发自定义事件count - changed
,并传递count
的最新值。 - 在父组件
Parent.svelte
中,引入子组件Child
,并通过on:自定义事件名
的方式监听子组件触发的count - changed
事件,在handleCountChange
函数中处理接收到的数据。