引言Vue3作为新一代的JavaScript框架,带来了许多改进和创新。其中,插槽(slot)和指令(directive)是两个重要的特性,它们提供了灵活且强大的组件定制能力。本文将深入探讨Vue3中...
Vue3作为新一代的JavaScript框架,带来了许多改进和创新。其中,插槽(slot)和指令(directive)是两个重要的特性,它们提供了灵活且强大的组件定制能力。本文将深入探讨Vue3中插槽与指令的实战应用,帮助开发者更高效地利用这些特性。
默认插槽是最常见的插槽类型,允许父组件在子组件内部填充内容。
<!-- 子组件 -->
<template> <div> <slot></slot> </div>
</template><!-- 父组件 -->
<template> <ChildComponent> <div>这是父组件提供的内容</div> </ChildComponent>
</template>当子组件需要多个插槽时,具名插槽非常有用。
<!-- 子组件 -->
<template> <div> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div>
</template><!-- 父组件 -->
<template> <ChildComponent> <template v-slot:header> <h1>标题</h1> </template> <p>主要内容</p> <template v-slot:footer> <p>页脚</p> </template> </ChildComponent>
</template>作用域插槽允许父组件访问子组件的数据。
<!-- 子组件 -->
<template> <div> <slot :user="user"></slot> </div>
</template>
<script>
export default { data() { return { user: { name: 'John Doe', age: 30 } }; }
}
</script><!-- 父组件 -->
<template> <ChildComponent> <template v-slot="{ user }"> <div>{{ user.name }} - {{ user.age }}</div> </template> </ChildComponent>
</template>自定义指令可以用于扩展DOM元素的行为。
// main.js
app.directive('focus', { mounted(el) { el.focus(); }
});<!-- 使用自定义指令 -->
<input v-focus />自定义指令可以包含生命周期钩子,例如inserted。
app.directive('focus', { inserted(el) { el.focus(); }
});自定义指令可以接受参数和修饰符。
<!-- 使用自定义指令,传递参数并使用修饰符 -->
<div v-color="'red'" :title="title" v-text="message | uppercase"></div>// main.js
app.directive('color', { bind(el, binding) { el.style.color = binding.value; }
});Vue3的插槽和指令为开发者提供了强大的定制能力。通过本文的实战解析,开发者可以更好地理解和应用这些特性,从而构建更灵活、更强大的Vue3应用。