vue2中使用jsx
# 背景
如果你写了很多 render 函数,可能会觉得下面这样的代码写起来很痛苦:
createElement(
'anchored-heading', {
props: {
level: 1
}
}, [
createElement('span', 'Hello'),
' world!'
]
)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
[
{ label: '最近更新时间', prop: 'update_time', align: 'center', visible: false },
{
label: '操作', align: 'center', 'min-width': '180px', render: (h, { row }) => {
return h('div',
[h('el-popconfirm', {
props: { title: '确定删除吗?', 'confirm-button-type': 'danger' },
class: 'mr-10',
on: {
confirm: () => { this.delItem(row) }
}
},
[h('el-button', { slot: 'reference', props: { size: 'mini', type: 'danger' }}, '删除')]),
h('el-button', { props: { size: 'mini', type: 'primary' }, nativeOn: { click: () => { this.editItem(row) } }}, '编辑')]
)
}
}
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
特别是对应的模板如此简单的情况下:
<anchored-heading :level="1">
<span>Hello</span> world!
</anchored-heading>
1
2
3
2
3
<el-popconfirm
title="确定删除吗?"
'confirm-button-type'="danger"
@confirm="delItem(row)"
>
<el-button slot="reference" size="mini" type="danger">删除</el-button>
</el-popconfirm>
<el-button size="mini" type="danger" @click="editItem(row)">编辑</el-button>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 安装使用JSX
# 安装babel插件
npm install @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props
# 使用
# babel7
- 配置
babel.config.js
module.exports = {
presets: ['@vue/babel-preset-jsx'],
}
1
2
3
2
3
如果你出现这个错误: Duplicate declaration "h" (This is an error on an internal node. Probably an internal error.)
试试这个(H函数传递)
module.exports = {
presets: [
[
'@vue/babel-preset-jsx',
{
injectH: false
}
]
]
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# babel 6
npm install babel-plugin-syntax-jsx babel-plugin-transform-vue-jsx babel-helper-vue-jsx-merge-props babel-preset-env --save-dev
- 配置
.babelrc
{
"presets": ["env"],
"plugins": ["transform-vue-jsx"]
}
1
2
3
4
2
3
4
上次更新: 2022/06/05, 20:31:36