vue使用JSX语法
如果你使用过react技术那不用担心,在vue里面使用JSX是差不多的。vue在大多数情况都是使用模板来创建页面,很少会有使用完全js编程,只有在大型项目或插件中使用。
如果你真的需要js来编写界面,vue提供一个render函数,与生命周期同级写法如下:
created(){
},
render(createElement){
}
1
2
3
4
5
6
2
3
4
5
6
render函数提供一个createElement方法,我们可以通过它来产生虚拟dom。
如下:使用该方法创建了一个div容器,容器内有两个元素img和span,我们可以通过这种嵌套的功能实现html模板。为了避免和标签style和class冲突,渲染函数中使用staticStyle和staticClass替换。
render(create){
return create('div', {
staticStyle: {
width: "400px",
height: "400px"
},
staticClass: "box"
on: {
click: function(e){
//dosomething
}
},
[{
'img',
{
staticClass: 'img-bg',
attrs: {
src: 'url'
}
}
},{
'span',
{
staticClass: 'title',
}
}]
})
}
<style lang="scss">
.box {
}
.img-bg {
}
.title {
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
这样的写法有个严重的问题:篇幅太长、不利于编写代码。于是就有了JSX,它是一种js的扩展语法。可参考React JSX
简单来说就是()内是html、{}内是JavaScript、js代码外层必须有html组件。下面介绍几种模板中的常规用法
return (
<div class="box" style="width: 400px;height: 400px">
<img src="url" class="img-bg">
<span class="title"></span>
</div>
);
1
2
3
4
5
6
2
3
4
5
6
# 组件使用
在render中使用组件跟在模板中使用是一样的,传递参数也没有变化。如下:
import comText from './com-text.vue'
...
components: {comText}
...
render(c){
return (
<comText text="123456"></comText>
)
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 样式、属性、事件绑定
绑定都通过单花括号
<div class="img-container" style={this.imgConStyle} onMouseover={this.mouseover}>
{
this.imgList.map(img => {
return <img src={img} class="img" onTouchstart={this.touchstart} onTouchend={this.touchend}/>
})
}
</div>
1
2
3
4
5
6
7
2
3
4
5
6
7
# v-if、v-for
在jsx没有v-if和v-for。要实现v-if可以通过三目运算符,实现v-for可以通过map,你也可以通过createElement函数中传递指令来实现。
<div class="tabs">
{
this.tabs.map((tab, index) => {
return <div class={index == this.current ? 'tab-on tab-item' : 'tab-off tab-item'} onClick={() => {this.clickTab(index)}}><span>{tab.name}</span></div>
})
}
<div style={this.sliderStyle}></div>
</div>
<!-- 指令 -->
createElement('div', {
directives: [{
name:"show",
rawName:"v-show",
value:true
}]
},[])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
提示
仅支持h5项目,小程序和app不会识别render函数
上次更新: 2025/09/05, 8:09:00