Vue 项目中 JSX 语法如何使用 scopedSlots

面试官:

  • Vue如何在 JSX 中使用 scopedSlots ?
  • scopedSlots 和 slot-scope 的区别

scopedSlots 和 slot-scope 的区别

 

  • 作用相同:都是作用域插槽
  • 场景不同:slot-scope 是模板语法,scopedSlots 则是编程式语法
  • 使用不同:在 template 中使用 slot-scope,在 render 函数中使用 scopedSlots

在 template 中如何使用

slot chac 


<div class="container">
  <slot name="header" :text="headerText"></slot>
  <slot :text="defaultText"></slot>
  <slot name="footer" :text="footerText"></slot>
</div>

在 render 函数中如何使用

render(h) {
  return h("div", { class: "container" }, [
    // 相当于 <slot name="header" :text="headerText"></slot>
    this.$scopedSlots.header({ text: this.headerText }),
    // 相当于 <slot :text="defaultText"></slot>
    this.$scopedSlots.default(this.defaultText),
    this.$scopedSlots.footer({ text: this.footerText })
  ]);
}

在 JSX 中如何使用

使用之前我们需要安装解析 JSX 语法的相关插件:

npm install\
  babel-plugin-syntax-jsx\
  babel-plugin-transform-vue-jsx\
  babel-helper-vue-jsx-merge-props\
  babel-preset-env\

配置 babel.config.js 文件

const plugins = []
plugins.concat('jsx-v-model', 'transform-vue-jsx')

module.exports = {
  plugins: [
    ...plugins,
  ]
}

使用 JSX 语法在 scopedSlots(作用域插槽)中如何书写呢?

const columns = function (h) {
  const columns = [
    { title: '用户名', dataIndex: 'username', scopedSlots: { customRender: 'username' } },
    { title: '操作',
      width: 80,
      dataIndex: 'action',
      customRender: (text, record, index) => {
        return <span>
          { ['edit', 'add'].includes(this.mode) &&
            <a on-click={this.handleDelete.bind(this, { text, record, index })} href="javascript:;">删除</a>
          }
        </span>
      },
  ]
  return columns
}
<a-table
  size="small" bordered
  rowKey="id"
  data-source={this.tableData}
  columns={columns.call(this, h)}
  {...{ scopedSlots: this.scopedSlotsList }}
/>

compunted: {
  scopedSlotsList () {
    const obj = {}
    obj['username'] = (text, record, index) => {
      return <p>text</p>
    }
    return obj
  }
},

更多信息,请查看:在 render 函数中,Vue 实例属性:$attrs、$props、$listeners 和 $scopedSlots的使用。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值