vue 渲染函数 & JSX

渲染函数 render

通过渲染函数渲染组件

Vue.component('myComponent', {
  render (h) { // createElement
    return h(
      'div', // HTML tag、自定义组件、异步组件
      { // 属性对象
        attrs: { // 标签属性
          id: 'wrap'
        },
        class: { // 类名
          'my-com': true
        },
        props: { // DOM 属性,props
          user: 'wdapp'
        },
        style: { // 样式
          color: 'red',
          fontSize: '18px'
        },
        on: { // 绑定事件
          mouseenter: function () {
            console.log('click')
          }
        },
        key: 'myKey', // 唯一key值
        ref: 'myRef', // 获取DOM元素的标识
      },
      [// 子节点
        "文本节点", //  文本节点
        h('h1', "内容"), // 虚拟节点
      ]
    )
  }
})

渲染后:

// html
<div id="wrap" class="my-com" style="color: red; font-size: 18px;">文本节点<h1>内容</h1></div>

JSX

通过以上方式创建虚拟DOM,语法比较繁琐。可以使用JSX(JavaScript XML)语法,配合createElement轻松的创建虚拟DOM。

Vue使用JSX语法,需要配合Babel插件进行解析。

import AnchoredHeading from './AnchoredHeading.vue'

new Vue({
  el: '#demo',
  render: function (h) {
    return (
      <AnchoredHeading level={1}>
        <span>Hello</span> world!
      </AnchoredHeading>
    )
  }
})

函数式组件

Vue.component('smart-list', {
  functional: true, // 函数式组件
  props: { // 属性
    items: {
      type: Array,
      required: true
    }
  },
  // context 上下文
  render: function (createElement, context) {
    return createElement(
      "button",
      context.data, // 把smart-list自定义组件的整个"数据对象"传递给button
      context.children // 把smart-list自定义组件的所有子节点传递给button
    )
  }
})

"数据对象": 指的是上文提到的createElement的第二个参数,之类包括 props、class、id等

使用组件:

<smart-list id="Smart" class="smart-list" @click="handelClick">Smart Btn</smart-list>

渲染为:

<button id="Smart" class="smart-list">Smart Btn</button>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值