在Vue3中使用JSX
在绝大多数情况下,Vue 推荐使用模板语法来创建应用。然而在某些使用场景下,我们真的需要用到 JavaScript 完全的编程能力。这时渲染函数就派上用场了。
如果你还不熟悉虚拟 DOM 和渲染函数的概念的话,请确保先阅读渲染机制章节。
要书写JSX的话需要安装 @vitejs/plugin-vue-jsx 包。
//vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'
export default {
plugins: [
vueJsx({
// options are passed on to @vue/babel-plugin-jsx
}),
],
}
配置完成后新建一个 .jsx 文件就可以开始书写了。
但是呢,Vue 推荐使用模板语法来创建应用,我们为什么用JSX呢!
我们这个业务需要点击一个按钮,然后查看详情出现一个弹窗,这个弹窗会出现详情列表。
如果用模板语法的话,需要定义一个是否显示弹窗的变量,点击这个按钮之后,要根据数据ID请求相应的数据详情,并将数据赋值给一个变量,显示弹窗的变量赋值为True ,将请求回来的数据传入弹窗组件中再由组件v-for展示出来。
如果用JSX呢。
只需要创建一个JSX文件:
import { defineComponent, ref } from "vue";
import { ElDialog, ElTable, ElTableColumn, ElButton } from "element-plus";
//编辑涉及主播弹窗
export default defineComponent({
name: "EditingInvolvesAnchors",
props: {
onClose: {
type: Function,
default: () => {},
},
},
setup(props) {
const dialogVisible = ref(true);
const handleClose = (done) => {
done();
props.onClose();
};
const tableData = [
{
date: "2016-05-03",
name: "Tom",
address: "No. 189, Grove St, Los Angeles",
},
{
date: "2016-05-02",
name: "Tom",
address: "No. 189, Grove St, Los Angeles",
},
{
date: "2016-05-04",
name: "Tom",
address: "No. 189, Grove St, Los Angeles",
},
{
date: "2016-05-01",
name: "Tom",
address: "No. 189, Grove St, Los Angeles",
},
];
const tableColumns = [
{ prop: "date", label: "利润名称" },
{ prop: "name", label: "金额" },
{ prop: "address", label: "日期" },
{ prop: "address", label: "状态" },
{ prop: "operation", label: "操作" },
];
return () => (
<ElDialog
modelValue={dialogVisible.value}
onUpdate:modelValue={(val) => (dialogVisible.value = val)}
title="涉及主播"
width="1000px"
beforeClose={handleClose}
>
<ElTable data={tableData}>
{tableColumns.map(({ prop, label }) => {
return (
<ElTableColumn prop={prop} label={label}>
{{
default: (scope) => {
if (prop === "operation") {
return <ElButton type="danger">删除</ElButton>;
}
return scope.row[prop];
},
}}
</ElTableColumn>
);
})}
</ElTable>
</ElDialog>
);
},
});
然后在点击事件里面传入 数据ID,并且渲染这个弹窗
import EditingInvolvesAnchorsComponent from "./editingInvolvesAnchors.jsx";
const vnode = h(EditingInvolvesAnchorsComponent, {
content: "id",
onClose: () => {
setTimeout(() => {
render(null, container);
container.remove();
}, 500);
},
});
render(vnode, container);
document.body.appendChild(container);
这样,在父组件内不用定义多余的变量,直接用js就可以操作弹窗了。 简洁!
以上,完结,撒花~