一、为什么要使用 JSX
-
优
-
灵活
- 相对于 template 更灵活,
- 赋予开发者许多编程能力,
- 让组件更加简单、明了、直观。
-
质量:结合 ts 类型检查提前发现错误
-
开发体验:结合 ts 语法提示会拥有更好的开发体验
-
-
劣
- 灵活:
- 学习转换成本、vue 特性写法 props、事件、指令、插槽等,
- 类型检查带来上手成本,
- 会损失一些运行时的性能。
二、JSX 是什么
- 不是模板、不是新语言
- 是 javascript 的语法扩展
三、基于 JSX 语法中使用 VUE 指令
- v-text、v-html、v-show 没变化
- v-model 使用上用调整,需要注意原生与自定义组件的区别, 使用方式:v-model={model.vue} or v-model={[model.jsx, 'value']}
- v-on 事件 以 js 原生驼峰语法 onClick
- v-slot 插槽 以对象的形式书写
- v-for、 v-bind、
v-if、v-else、v-else-if用 js 语法代替
四、JSX在Vue3中的使用
// 表达式
const hi = <div>Hi, {guys} </div>
const component = Math.random() > 0.5 ? <CommponentA /> : <CommponentB />
//函数式组件
const App = () => <div></div>;
//在 render 中使用
const App = {
render() {
return <div>Vue 3.0</div>;
},
};
import { withModifiers, defineComponent } from "vue";
const App = defineComponent({
setup() {
const count = ref(0);
const inc = () => {
count.value++;
};
return () => (
<div onClick={withModifiers(inc, ["self"])}>{count.value}</div>
);
},
});
//动态绑定:
const placeholderText = "email";
const App = () => <input type="email" placeholder={placeholderText} />;
//列表渲染
const data = [{
id: 1,
name: 'xiaoming'
}, {
id: 2,
name: 'xiaohong'
}]
const element = data.map(item => {
return <div>{ item.name }</div>
})
// style 样式绑定
const width = '100px'
const element = <div style={{ width, fontSize: '20px' }}></div>
//事件绑定
const confirm = () => {
// 确认提交
}
<button onClick={()=> confirm()}>确定</button>
//绑定属性
const props={a:'123',b:'456'}
<Component {...props} />
<!-- v-model 用法-->
<input v-model={val} />
<input v-model:argument={val} />
<input v-model={[val, ["modifier"]]} />
<A v-model={[val, "argument", ["modifier"]]} />
插槽
注意: 在
jsx
中,应该使用v-slots
代替v-slot
const App = {
setup() {
const slots = {
default: () => <div>A</div>,
bar: () => <span>B</span>,
};
return () => <A v-slots={slots} />;
},
};
参考链接
babel-plugin-jsx/README-zh_CN.md at dev · vuejs/babel-plugin-jsx (github.com)