在 Vue.js 中,props 是父组件用来传递数据到子组件的一种机制。当你构建一个可复用的 Vue 组件时,props 允许你指定哪些数据是可以从父组件传递到子组件中的。子组件不能修改 props 传递的数据,因为这会导致数据流混乱,Vue 官方推荐使用事件($emit)来通知父组件更新数据。

如何定义 Props

在子组件中,你可以通过组件的 props 选项来声明需要接收的 props。这个选项是一个包含所有需要接收的 prop 及其类型的对象

<template> <div> <h2>这里是子组件</h2> <slot></slot> <!-- 默认插槽 --> </div> </template> <script> export default { name: 'Child' } </script>

父组件使用 Child.vue 并填充默认插槽:

vue<template> <div> <child> <p>这是来自父组件的内容,填充到了子组件的默认插槽中。</p> </child> </div> </template> <script> import Child from './Child.vue' export default { components: { Child } } </script>

具名插槽

子组件 Child.vue 使用具名插槽:

vue<template> <div> <h2>这里是子组件</h2> <slot name="header"></slot> <p>这是一些默认内容。</p> <slot name="footer"></slot> </div> </template> <script> export default { name: 'Child' } </script>

父组件使用具名插槽:

vue<template> <div> <child> <template v-slot:header> <p>这是头部内容。</p> </template> <template v-slot:footer> <p>这是底部内容。</p> </template> </child> </div> </template> <script> import Child from './Child.vue' export default { components: { Child } } </script>

作用域插槽

子组件 Child.vue 传递数据到作用域插槽:

vue<template> <ul> <li v-for="item in items" :key="item.id"> <slot name="item" :item="item"> {{ item.text }} <!-- 默认内容 --> </slot> </li> </ul> </template> <script> export default { data() { return { items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' } ] } } } </script>

父组件使用作用域插槽并访问传递的数据:

vue<template> <div> <child> <template v-slot:item="{ item }"> <span style="color: blue;">{{ item.text }}</span> </template> </child> </div> </template> <script> import Child from './Child.vue' export default { components: { Child } } </script>

通过这些示例,你可以看到Vue中的Slots如何使组件之间的内容分发变得更加灵活和强大。

最后修改:2024 年 08 月 31 日
如果觉得我的文章对你有用,请随意赞赏