问题提出
vue3 在使用模板语法时,似乎并不可以像 React 的 jsx 文件一样在导出一个默认组件函数的同时,定义一些不需要复用的简单组件。
这就导致很多 vue3 开发者会选择把那些组件定义在 src/components 文件夹中,但是这样导致了一些问题:
- 简单组件不方便命名
- 组件与页面联系弱,难以阅读
- 组件不需要复用,一般逻辑上不应该单独写成文件
- 组件定义过于复杂
- 组件与页面数据交互困难,需要额外定义 props
- 组件样式与页面样式分离
解决方案
其实我们可以在 vue 的 setup 中书写 jsx 语法来定义简单组件。
启用 jsx 语法,vite.config.js 中:
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [vue(), vueJsx()],
})
模板中使用 jsx 语法,lang="jsx(/tsx)",vue 文件中:
<script setup lang="tsx">
import { ElMessageBox } from 'element-plus'
import { ref } from 'vue'
const model1 = ref('')
// 使用外部变量,更加简洁
const Comp1 = () => <input type="text" v-model={model1.value} />
// 定义逻辑,更加清晰
const Comp2 = () => {
const model2 = ref('')
return <input type="text" v-model={model2.value} />
}
// 在函数中使用
ElMessageBox.confirm(Comp2)
</script>
<template>
<-- 直接在 template 中使用 -->
<Comp1 />
</template>
<style scoped></style>