美文网首页
vue 渲染函数 & JSX

vue 渲染函数 & JSX

作者: wdapp | 来源:发表于2020-02-16 21:40 被阅读0次

    渲染函数 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>
    

    相关文章

      网友评论

          本文标题:vue 渲染函数 & JSX

          本文链接:https://www.haomeiwen.com/subject/tgamfhtx.html