uniapp componentplaceholder 的使用方法

在uniapp中使用componentplaceholder时遇到了一些问题,想请教一下具体的使用方法。比如这个组件应该放在什么位置?它有哪些常用的属性可以配置?在页面加载时如何控制它的显示和隐藏?能否结合示例代码说明一下最佳实践?

2 回复

在uni-app中,componentplaceholder是用于自定义组件占位符的属性。使用方法:

  1. 在页面json配置:
"usingComponents": {
  "my-component": "/components/my-component"
}
  1. 在页面模板:
<my-component component-placeholder="loading..."></my-component>

当组件加载时显示"loading…"占位文本,直到组件渲染完成。


在 UniApp 中,componentplaceholder 是一个组件占位符属性,主要用于 小程序端(如微信小程序),在自定义组件中定义插槽(slot)时,为未填充内容的插槽提供占位显示。当父组件未向插槽传递内容时,占位内容会显示;传递内容后,占位内容被替换。

使用方法

  1. 在自定义组件中配置
    在自定义组件的 .vue 文件中,通过 componentPlaceholder 属性为插槽设置占位内容。
    示例代码

    <!-- 子组件 child.vue -->
    <template>
      <view>
        <slot name="header">
          <!-- 若无内容,显示占位 -->
          <text>默认头部</text>
        </slot>
        <view>主体内容</view>
      </view>
    </template>
    
    <script>
    export default {
      componentPlaceholder: {
        // 键为插槽名,值为占位组件的选择器或模板
        header: "text" // 使用原生组件"text"作为占位
      }
    }
    </script>
    
  2. 在父组件中使用
    父组件可选择性向插槽传递内容。若不传递,显示占位;若传递,占位被替换。
    示例代码

    <!-- 父组件 -->
    <template>
      <view>
        <!-- 不传递内容:显示子组件中的占位文本"默认头部" -->
        <child-component />
        
        <!-- 传递内容:占位被替换为自定义内容 -->
        <child-component>
          <template v-slot:header>
            <text>自定义头部内容</text>
          </template>
        </child-component>
      </view>
    </template>
    

注意事项

  • 平台限制:仅小程序端有效(H5 和 App 端忽略此属性)。
  • 占位值类型:通常使用小程序原生组件(如 viewtext)作为占位元素。
  • 兼容性:确保 UniApp 版本支持此属性(常见于较新版本)。

通过 componentPlaceholder 可提升组件灵活性,避免插槽为空时布局错乱。

回到顶部