vue3 jsx/tsx 语法 使用css样式,循环,事件,插槽
tsconfig.json
当使用 TSX 语法时,确保在 tsconfig.json 中配置了 "jsx": "preserve"
,这样的 TypeScript 就能保证 Vue JSX 语法转换过程中的完整性。
从 Vue 3.4 开始,Vue 不再隐式注册全局 JSX 命名空间。要指示 TypeScript 使用 Vue 的 JSX 类型定义,请确保在你的 tsconfig.json 中包含以下内容:
json
{
"compilerOptions": {
"jsxImportSource": "vue",
"jsx": "preserve",
}
}
1
2
3
4
5
6
2
3
4
5
6
使用
函数式组件使用
defineComponent + setup 使用
使用样式
使用 ref 等变量
TIP
在 JSX 表达式中,使用大括号来嵌入动态值在 JSX 表达式中,ref 不能自动解包 需要 .value
v-on 事件绑定写法
以 on 开头,并跟着大写字母的 props 会被当作事件监听器。比如,onClick 与模板中的 @click 等价。
事件修饰符
组件
vue
export default () => {
return <div>tsx-children</div>;
};
1
2
3
2
3
tsx-children.tsx
vue
import TsxChildren from "./tsx-children";
export default () => {
return (
<div>
<TsxChildren />
</div>
);
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
tsx-father.tsx
vue
import TsxChildren from "./tsx-children";
export default {
setup() {
return () => {
return (
<>
<TsxChildren />
</>
);
};
},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
tsx-father.tsx
插槽 slot
默认插槽
tsx-children.tsx
vue
export default (props, { slots }) => {
return (
<>
<div class="default">{slots.default?.()}</div>
</>
);
};
1
2
3
4
5
6
7
2
3
4
5
6
7
tsx-father.tsx
vue
import TsxChildren from "./tsx-children";
export default () => {
return (
<div>
<TsxChildren>
{{
default: () => <p>我是默认插槽的内容</p>,
}}
</TsxChildren>
</div>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
具名插槽
tsx-children.tsx
vue
export default (props, { slots }) => {
return (
<>
<div class="default">{slots.default?.()}</div>
{/* 传递 msg */}
<div class="footer">{slots.footer?.({ msg: "footer 插槽" })}</div>
</>
);
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
tsx-father.tsx
vue
import TsxChildren from "./tsx-children";
export default () => {
return (
<div>
<TsxChildren>
{{
default: () => <p>我是默认插槽的内容</p>,
// 解构 msg 值,使用
footer: ({ msg }) => <p>我是-{msg}-的内容</p>,
}}
</TsxChildren>
</div>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15