Skip to content
On this page

Vue 中的 render 函数的 jsx 写法

v-model 写法(v-bind v-on)

js
render() {
    // 在cli4以后创建的项目已经支持直接在jsx中v-model了
    // 但是,只有prop是value并且event是input的默认情况适用
    return <input v-model={this.value} />

    // 其他情况或者较低的版本还是要拆开写
    // 同时实例下v-on v-bind的写法
    return (
      <input
        value={this.value}
        onInput={(val) => {
          this.value = val
        }}
      />
    )
  }

v-if v-for 的写法

这就很简单了,因为是 jsx 所以拥有原生的 js 能力

js
render() {
    // v-if
    return bool && <div />
    // v-if v-else
    return bool ? <div /> : <div />
    // v-for
    return (
      <div>
          {this.arr.map((item) => {
            return <div>{item}</div>
          })}
      </div>
    )
  }

插槽 slot 写法

js
render() {
    // 子组件中设置插槽写法
    // 默认插槽做defalut,其他命名插槽为其名称
    return <div>{this.$slots.default}</div>

    // 父组件中使用插槽
    return (
      <Child
        scopedSlots={{
          // 默认插槽
          default: (scope) => {
            return <div>return插槽内容</div>
          },
          // 命名插槽
          slotName: (scope) => {
            return <div>return插槽内容</div>
          },
        }}
      />
    )

    // 当然用了jsx,更建议把插槽内容作为一个变量
    // 简洁可读性强点
    const slot = <div>return插槽内容</div>
    return (
      <Child
        scopedSlots={{
          default: (scope) => slot,
        }}
      />
    )

  }

$attrs $listeners 写法

二次封装 ui 框架时常用的属性

js
render() {
    return (
      <div {...{ attrs: this.$attrs, on: this.$listeners }}/>
    )
  }

上次更新于: