通常开发vue我们使用的是模板,其实还有和react相同的语法,那就是render函数,支持jsx语法。
Vue 的模板实际是编译成了 render 函数。
Vue使用jsx语法
- 安装npm依赖
babel-plugin-syntax-jsx
babel-plugin-transform-vue-jsx
babel-helper-vue-jsx-merge-props
- 修改 .babelrc
{
"plugins": ["transform-vue-jsx"]
}
- 使用
renderContent (h, {node, data, store}) {
return (
<span>
<span>
<span>{node.label}</span>
</span>
<span style="float: right; margin-right: 20px">
<el-button size="mini" on-click={ () => this.append(store, data) }>Append</el-button>
<el-button size="mini" on-click={ () => this.remove(store, data) }>Delete</el-button>
</span>
</span>
)
}
vue 环境下的 jsx的语法
render (h) {
return (
<div
id="foo" // 属性
domPropsInnerHTML="bar" // DOM
onClick={this.clickHandler} // 事件
nativeOnClick={this.nativeClickHandler}
class={{ foo: true, bar: false }}
style={{ color: 'red', fontSize: '14px' }}
key="key"
ref="ref"
refInFor
slot="slot">
</div>
)
}
DOM属性要加domProps前缀 class 和 style 却不需要,因为这两个是特殊的模块(react的class用的是className,vue用的class) 事件监听是以“on”或者“nativeOn”为开始
上面的jsx语法会被编译成
render (h) {
return h('div', {
props: { msg: 'hi' }, // Component props
attrs: { id: 'foo' }, // normal HTML attributes
domProps: { innerHTML: 'bar' }, // DOM props
// Event handlers are nested under "on", though
// modifiers such as in v-on:keyup.enter are not
// supported. You'll have to manually check the
// keyCode in the handler instead.
on: {
click: this.clickHandler
},
// For components only. Allows you to listen to
// native events, rather than events emitted from
// the component using vm.$emit.
nativeOn: {
click: this.nativeClickHandler
},
// class is a special module, same API as `v-bind:class`
class: {
foo: true,
bar: false
},
// style is also same as `v-bind:style`
style: {
color: 'red',
fontSize: '14px'
},
// other special top-level properties
key: 'key',
ref: 'ref',
// assign the `ref` is used on elements/components with v-for
refInFor: true,
slot: 'slot'
})
}
jsx语法编写vue模版组件时,注意连接符要转换成驼峰式,除了v-show 指令外内置的指令都不会生效。 自定义指令可以使用“v-name={value}”语法,如果要支持指令参数和modifier可以用 “v-name=” 示例:
<script>
import Vue from 'vue';
Vue.directive('my-bold', {
inserted: function (el) {
el.style.fontWeight = 900;
}
})
export default {
props: ['onClick', 'isShow'],
data() {
return {
test: 123
};
},
methods: {
afterLeave() {
console.log('afterLeave')
}
},
render() {
const directives = [
{ name: 'my-bold', value: 666, modifiers: { abc: true } }
];
return (
<transition onAfterLeave={this.afterLeave} name="fade">
<div class="test" onClick={this.onClick} v-show={ this.isShow } v-my-bold>
{this.test}
{this.isShow + ''}
</div>
</transition>
);
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s
}
.fade-enter, .fade-leave-to {
opacity: 0
}
</style>