什么是JSX?
JSX就是Javascript和XML结合的一种格式。React发明了JSX,利用HTML语法来创建虚拟DOM。当遇到<,JSX就当HTML解析,遇到{就当JavaScript解析.
我为什么要在vue中用JSX?
想折腾一下呗,开玩笑.最开始是因为近期在学习react,在里面体验了一把jsx语法,发现也并没有别人说的很难受的感觉啊,于是就想尝试在vue中也试下,废话不多说,先来用代码来看下两者的区别吧.
ps:vue中大部分场景是不需要用render函数的,还是用模板更简洁直观.
使用template
// item.vue
<template>
<div>
<h1 v-if="id===1">
<slot></slot>
</h1>
<h2 v-if="id===2">
<slot></slot>
</h2>
<h3 v-if="id===3">
<slot></slot>
</h3>
<h4 v-if="id===4">
<slot></slot>
</h4>
</div>
</template><script>
export default {
name: "item",
props:{
id:{
type:Number,
default:1
}
}
}
</script>
item组件中就是接收父组件传过来的id值来显示不同的h标签,v-if可以说用到了”极致”,而且写了很多个冗余的slot
使用render函数和jsx
// item.vue
<script>
export default {
name: "item",
props:{
id:{
type:Number,
default:1
}
},
render(){
const hText=`
<h${this.id}>${this.$slots.default[0].text}</h${this.id}>
`
return <div domPropsInnerHTML={hText}></div>
}
}
</script>
再加上父组件来控制props的值。父组件不做对比还用传统的template格式,
// list.vue
<template>
<div>
<h-title :id="id">Hello World</h-title>
<button @click="next">下一个</button>
</div>
</template><script>
import Title from './item'
export default {
name: "list",
data() {
return {
id:1
}
},
components: {
"h-title":Title
},
methods:{
next(){
++this.id
}
}
}
</script>
运行后页面就渲染出了h1 or h2 or h3标签,同时slot也只有一个,点击切换props的值,也会显示不同的h标签。第二种写法虽然不是很直接,但是省去了很多冗余代码,页面一下清爽了很多。
没了v-if,v-for,v-model怎么办?










