插槽在vue的开发中显得很有用处,今天我们就来说说如何通过插槽来给子组件分配内容?
一些情况下我们会希望能和 HTML 元素一样向组件中传递内容:
<AlertBox> Something bad happened. </AlertBox>
我们期望能渲染成这样:
这可以通过 Vue 的自定义 <slot> 元素来实现:
<template> <div class="alert-box"> <strong>This is an Error for Demo Purposes</strong> <slot /> </div> </template> <style scoped> .alert-box { /* ... */ } </style>
如上所示,我们使用 <slot> 作为一个占位符,父组件传递进来的内容就会渲染在这里。
我们通过一个实例来加深对插槽的理解。
App.vue
<script> import AlertBox from './AlertBox.vue' export default { components: { AlertBox } } </script> <template> <AlertBox> Something bad happened. </AlertBox> </template>
AlertBox.vue
<template> <div class="alert-box"> <strong>Error!</strong> <br/> <slot /> </div> </template> <style scoped> .alert-box { color: #666; border: 1px solid red; border-radius: 4px; padding: 20px; background-color: #f8f8f8; } strong { color: red; } </style>
通过以上内容我们知道了vue 中如何通过插槽来给子组件分配内容。感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!