Previous articles:
- Vue3 hasn’t even started yet. – Just want to give up
- Vue3-vuex-typescript trampling tour
preface
JSX has been supported since VUe2, but not in a friendly way. With the support for typescript in Vue3, TSX is becoming more and more popular. We won’t compare template with JSX.
- Template is suitable for students who are used to defining HTML/CSS first and then writing logical JS
- JSX/TSX is more suitable for students who are used to writing code in logical order, HTML/CSS/JS cross writing order
Personally, I prefer React. JSX/TSX can generate components dynamically through JS, but I don’t like the writing method of vue template controlled by :is.
The body begins…
The preparatory work
- 1. Install typescript version of Vue3
yarn create @vitejs/app
- 2. Install @ vitejs/plugin – vue – JSX
yarn add -D @vitejs/plugin-vue-jsx
- 3. Configure vite. Coonfig. Ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx({})],
});
Copy the code
- 3. Configure tsconfig. Json
{
"compilerOptions": {
"jsx": "preserve"."jsxFactory": "h"."jsxFragmentFactory": "Fragment",}}Copy the code
vue3 + tsx
// TsxTest.tsx
import { FunctionalComponent as FC, defineComponent, reactive, onMounted } from 'vue';
// Stateless components
const FcNode: FC<{ data: number} > =({ data }) = > {
return (
<>
<hr />
<div>Child component: {data < 10?<span>{data}</span> : <h1>{data}</h1>}
</div>
</>)};// State components need to use defineComponent
export default defineComponent({
name: 'TsxTest'.setup() {
const data = reactive({ count: 0 });
onMounted(() = > {
data.count = 5;
});
const clickHandler = () = > data.count++
return () = > (
<>
<span style={{ marginRight: '10px' }}>{ data.count }</span>
<button onClick={clickHandler}>+</button>
<FcNode data={data.count}/>
</>)}})Copy the code
The end of the
You’ll notice that Vue3 + TSX is very similar to React. React has a lower learning cost. Also confirmed the old saying: through the ages a copy of the article!
Join us at ❤️
Bytedance Xinfoli team
Nice Leader: Senior technical expert, well-known gold digger columnist, founder of Flutter Chinese community, founder of Flutter Chinese community open source project, well-known developer of Github community, author of dio, FLY, dsBridge and other well-known open source projects
We look forward to your joining us to change our lives with technology!!
Recruitment link: job.toutiao.com/s/JHjRX8B