Vue2 命名插槽和作用域插槽

Posted on 2024-05-14 12:34  生之不止,思之不息  阅读(38)  评论(0)    收藏  举报

在Vue中,使用JSX可以更灵活地定义组件和插槽。下面将通过JSX语法来演示普通插槽、作用域插槽以及命名插槽的使用。

1. 普通插槽(Slots)和命名插槽

子组件(ChildComponent.jsx)

export default {
  name: 'ChildComponent',
  render(h) {
    return (
      <div>
        <header>
          {this.$slots.header}
        </header>
        <main>
          {this.$slots.default}
        </main>
        <footer>
          {this.$slots.footer}
        </footer>
      </div>
    );
  }
}

父组件(ParentComponent.jsx)

import ChildComponent from './ChildComponent.jsx';

export default {
  name: 'ParentComponent',
  render(h) {
    return (
      <div>
        <ChildComponent>
          <template slot="header">
            <h1>这是头部内容</h1>
          </template>
          <p>这是主要内容</p>
          <template slot="footer">
            <p>这是底部内容</p>
          </template>
        </ChildComponent>
      </div>
    );
  }
}

在这个例子中,子组件定义了一个默认插槽和两个命名插槽(headerfooter)。父组件通过slot属性为每个命名插槽提供了相应的内容。

2. 作用域插槽(Scoped Slots)和命名插槽

子组件(ChildComponent.jsx)

export default {
  name: 'ChildComponent',
  data() {
    return {
      title: '欢迎光临',
      user: {
        name: 'Alice',
        age: 25
      }
    };
  },
  render(h) {
    return (
      <div>
        {this.$scopedSlots.header({
          title: this.title
        })}
        {this.$scopedSlots.default({
          user: this.user
        })}
        {this.$slots.footer}
      </div>
    );
  }
}

父组件(ParentComponent.jsx)

import ChildComponent from './ChildComponent.jsx';

export default {
  name: 'ParentComponent',
  render(h) {
    return (
      <div>
        <ChildComponent scopedSlots={{
          header: ({ title }) => <h1>{title}</h1>,
          default: ({ user }) => (
            <div>
              <p>用户名称: {user.name}</p>
              <p>用户年龄: {user.age}</p>
            </div>
          )
        }}>
          <template slot="footer">
            <p>这是底部内容</p>
          </template>
        </ChildComponent>
      </div>
    );
  }
}

在这个例子中,子组件通过作用域插槽向父组件传递数据,包括 titleuser 对象。父组件使用scopedSlots属性为每个命名插槽提供了内容,并可以访问子组件传递的数据。

总结

  • 普通插槽和命名插槽 允许父组件向子组件传递静态内容,并且可以在子组件中定义多个插槽以更灵活地组织内容。
  • 作用域插槽和命名插槽 允许子组件向父组件传递数据,父组件可以根据这些数据动态生成插槽内容,并且可以为多个插槽提供动态内容。

通过结合使用命名插槽和作用域插槽,以及JSX语法,我们可以实现更加复杂和灵活的组件内容传递和数据交互。JSX语法使得这种方式更加简洁和直观。

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3