心路历程:vue2.0+webpack+koa2 先后端同构实践(二)

vue2.0之JSX初体验

JSX入门

JSX来至于React,上手并不复杂,在Vue中使用只有小部分差别css

标签必须闭合

在 JSX 中, <MyComponent /> 是合法的,而 <MyComponent> 就不合法。
全部的标签都必须闭合,能够是自闭和的形式,也能够是常规的闭合。react

<div />和<div></div> 是等价的。git

标签与组件

要渲染 HTML 标签,只需在 JSX 里使用小写字母开头的标签名。
要渲染 React 组件,只需建立一个大写字母开头的本地变量。es6

分支 if/else

if-else-in-JSXgithub

可是实践时,发现vue2.0并不支持,也许是个人姿式不对,稍后填坑。babel

发现多是一个bug插入JSX中的变量为空字符串时致使以下问题,已经提了issueless

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. Bailing hydration and performing full client-side render.

循环 for

编辑器中格式化插件支持

推荐插件js-beautify,对html+css(less)+js(es6)都良好支持。
支持JSX只要在.jsbeautify文件中添加以下配置:编辑器

{
    ....
    "e4x": true
    ....
}

从官网例子开始

import Column from './column'

export default {
  props: ['row'],
  serverCacheKey: props => {
    return props.row.id + '::' + props.row.items.length
  },
  render (h) {
    return (
      <tr>
        <th>{this.row.id}</th>
        {this.row.items.map(item => <Column item={item}/>)}
      </tr>
    )
  }
}

源码

注意点

render 方法的参数名必须是h,缘由没深究研究,github有提到。

给本身挖坑

开始看源码时,误将render写法等同于如下代码

render: h => {
    return (
        ...
        <th>{this.row.id}</th>
        ...
    )
}

致使编译结果this 被编译成 undefined

render: function render(h) {
    return h(
        ...
          "th",
          [undefined.row.id]
        ...
    )
}

做者的回复

尤大大已经解答了这个问题

arrow functions uses lexical this, you can only use normal functions if you want this.

箭头函数

回头翻看了下阮老师写的《ECMAScript 6 入门》箭头函数章节,以前看时没能理解到位。

函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

使用JSX实现Vue2.0功能的一些方案

插入HTML格式与filters的使用

基本和JSX同样

Vue组件中的slot[name]标签替代方案

若是是单slot能够经过子节点表达式插入,一个组件有多solt时怎么处理呢?

如何实现双向绑定?

目前的方案基于Vuex来作单向数据流,告别双向绑定。到时候遇到作表单的时候再来仔细考虑下这个问题。

相关文章
相关标签/搜索