You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// normal attributes or component props.id="foo"// DOM properties are prefixed with `domProps`domPropsInnerHTML="bar"// event listeners are prefixed with `on` or `nativeOn`onClick={this.clickHandler}nativeOnClick={this.nativeClickHandler}// other special top-level propertiesclass={{foo: true,bar: false}}style={{color: 'red',fontSize: '14px'}}key="key"ref="ref"// assign the `ref` is used on elements/components with v-forrefInForslot="slot"
对应render function来看
render function
Vue JSX
‘class’: { foo: true, bar: false }
class={{ foo: true, bar: false }}
style: { color: 'red', fontSize: '14px' }
style={{ color: 'red', fontSize: '14px' }}
attrs: { id: 'foo' }
id="foo"
props: { myProp: 'bar'}
myProp="bar"
domProps: { innerHTML: 'baz'}
domPropsInnerHTML='baz'
on: { click: this.clickHandler }
onClick={this.clickHandler}
nativeOn: { click: this.nativeClickHandler }
nativeOnClick={this.nativeClickHandler}
slot: 'name-of-slot'
slot="name-of-slot"
key: 'myKey'
key="myKey"
ref: 'myRef'
ref="myRef"
我要把如下通用下拉菜单用JSX写出来:
<el-dropdown@command="handleCityCommand"><spanclass="el-dropdown-link">
{{spanCity}}<iclass="el-icon-arrow-down el-icon--right"></i></span><el-dropdown-menuslot="dropdown"><el-dropdown-itemv-for="(value, key) in commandCityList" :key="key" :command="key">
{{value}}
</el-dropdown-item></el-dropdown-menu></el-dropdown>
渲染函数
使用
Element UI 提供了渲染表头的函数
render-header
,render-header
就是一个render function,格式是这样的:这个createElement有三个参数:
'div'
,'span'
,也可以是组件的标签名,比如'el-dropdown'
。<span>你好</span>
,那么这第三个参数就是'你好'
。 如果是Array的话,第一项就是标签里的字符串,后几项都是createElement
,代表了这个标签里嵌套的标签们。第二个参数在官方文档里写的很清楚,这里复制过来:
搞明白了这些,就可以开始写渲染函数了。
比如我要实现一个下拉菜单像这样的下拉菜单:
在HTML里是这样写的:
在vue里就可以写成这样:
写完之后,发现每个dropdown item都要重复写,于是优化了一下,实现了下拉菜单的通用写法:
于是,对于以下数据:
我可以写出这样的render function:
最后,在表格中绑定这个函数
就可以得到开头的那个表头了。
JSX
看到这里,你或许觉得,光实现一个下拉菜单就要写这么多代码,有没有简单的方法呢?
官方文档里介绍了一个Babel插件,用于在Vue中使用JSX语法,写起来就简单多了。
https://github.com/vuejs/babel-plugin-transform-vue-jsx
用法也非常简单,首先
在
.babelrc
中加入:然后你就可以开始使用JSX语法了。要注意的是,这里不能再写
createElement
了,要写成h
。将
h
作为createElement
的别名是Vue生态系统中的一个通用惯例,实际上也是JSX所要求的,如果在作用域中h
失去作用,在应用中会触发报错。我们就可以把render function写成这样:
你一定发现了,这边的属性名有所变化了,比如
on:{command:handleCommand}
变成了onCommand
。文档里是这样写的:
对应render function来看
我要把如下通用下拉菜单用JSX写出来:
注意
v-for
在这边要用array.map()
来实现,写出来是这样的:用了JSX语法之后,渲染函数就回到了更接近于模板的语法上了。
参考资料
The text was updated successfully, but these errors were encountered: