1. what?
①. JSX是一种Javascript的语法扩展:
JSX = Javascript + XML
②. 在Javascript里面写XML,因为JSX的特性:
a. 具备了Javascript的灵活性.
b. 又兼具html的语义化和直观性.
2. why?
①. 业务中,需要使用渲染函数(render function)来抽象组件:
a. 官方的渲染函数:
createElement(
'anchored-heading', {
props: {
level: 1
}
}, [
createElement('span', 'Hello'),
' world!'
]
)
b. 对应的模板:
<anchored-heading :level="1">
<span>Hello</span> world!
</anchored-heading>
②. 非常不直接、难维护. => jsx上场
3. how?
(1). 初始化:
①. 安装:
$ vue create vue-jsx
$ npm install @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props
②. 配置.babelrc:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
['@vue/babel-preset-jsx',
{
'injectH': false
}]
]
}
③. 在Vue中使用JSX,需要安装Babel插件:
https://github.com/vuejs/jsx
(2). 基础内容:
const inputAttrs = {
type: 'email',
placeholder: 'Enter your email'
}
render() {
return (
<div>
{/* 纯文本 */}
<p>hello, I am Gopal</p>
{/* 动态内容 */}
<p>hello { this.msg }</p>
{/* 动态输入框 */}
<input type="email" placeholder={this.placeholderText} />
<input {...{ attrs: inputAttrs }} /> // 批量绑定属性
{/* 自定义组件 */}
<myComponent></myComponent>
{/* 展开一个对象 */}
<button {...this.largeProps}></button>
</div>
);
}
注:
①. 动态输入框:
v-bind:placeholder="this.placeholderText" => placeholder={this.placeholderText}