vue $scopedSlots作用域插槽

<body>
  <div id="app">
    <my-component>
      <h1 slot-scope="props">{{props.text}}</h1>
    </my-component>
  </div>
  <script>
    Vue.component('my-component',{
      render: function (createElement) {
        return createElement('div',[createElement('div',{domProps:{innerHTML:'this child div'}}),
          this.$scopedSlots.default({
            text:'hello world'
          })
        ])
      }
    })
   var vm = new Vue({
    el:'#app',
   })
  </script>
</body>
### Vue.js 使用 Scoped Slots 示例及常见问题解决 #### 一、Scoped Slots 基本概念 在 Vue.js 中,`$scopedSlots` 是组件实例上的一个属性,专门用于访问带有作用域插槽内容。这使得父组件可以向子组件传递数据,并让子组件能够基于这些数据渲染特定的内容[^1]。 #### 二、基本用法示例 下面是一个简单的例子展示如何使用 `v-slot` 指令定义带参数的作用域插槽: ```html <!-- 子组件 ChildComponent.vue --> <template> <div class="child"> <!-- 定义具名插槽并传入 props 数据 --> <slot name="header" :text="'Hello from child'"></slot> <p>Some content</p> <slot></slot> <footer> <slot name="footer" :items="[1,2,3]" /> </footer> </div> </template> ``` ```html <!-- 父组件 ParentComponent.vue --> <template> <ChildComponent v-slot:default="{ text }"> {{ text }} </ChildComponent> <ChildComponent> <!-- 默认插槽 --> Default Slot Content </ChildComponent> <ChildComponent> <!-- 具名插槽 header --> <template #header="{ text }"> <h1>{{ text }}</h1> </template> <!-- 具名插槽 footer --> <template slot="footer" slot-scope="{ items }"> <ul> <li v-for="(item, index) in items" :key="index">{{ item }}</li> </ul> </template> </ChildComponent> </template> ``` 上述代码展示了如何通过 `v-slot` 来接收来自子组件的数据,并将其作为模板的一部分进行显示[^2]。 #### 三、JSX 中的应用 当采用 JSX 编写时,语法略有不同。可以通过解构函数参数的方式来获取作用域内的变量: ```jsx // React-like JSX style with vue-class-component or similar setup. render(h){ return ( <ChildComponent scopedSlots={{ default(props){return (<span>{props.text}</span>)}, header(props){return (<h1>{props.text}</h1>)}, footer({items}){return( <ul> {items.map((i,idx)=><li key={idx}>{i}</li>)} </ul>) } }}/> ) } ``` 此片段说明了即使是在 JSX 上下文中也可以方便地利用 scoped slots 功能。 #### 四、Vue 3 更新要点 随着 Vue 版本升级到 3.x,在处理 scoped slots 方面有了更简洁的方式——移除了 `$scopedSlots` 属性而统一成单一的对象形式 `$slots` 。这意味着现在可以直接通过对象键值对的形式来操作所有的插槽,包括命名插槽和默认插槽[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值