uni-app Vue3页面模板、样式、TS文件分离

前言

如果页面的逻辑比较复杂的时候建议进行模板、样式、TS文件分离,这样有助于代码的查看和开发过程中的自动格式化。

格式化在只格式化TS/JS的时候性能远远高于模板和脚本混合的情况。

https://www.psvmc.cn/article/2025-03-17-vue3-ts-separation.html

页面

模板

index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<view class="content">
<view class="text-area">
<text class="title">{{ title }}</text>
</view>
</view>
</template>

<script lang="ts" setup>
import { usePage } from './index';

const { title } = usePage();
</script>

<style lang="scss">
@import 'index.scss';
</style>

TS

index.ts

1
2
3
4
5
6
7
8
9
10
11
12
import { ref, onMounted } from 'vue';

export function usePage() {
const title = ref('首页');

onMounted(() => {
console.info('onMounted', title.value);
});
return {
title
};
}

样式

index.scss

1
2
3
4
.title {
font-size: 36rpx;
color: deepskyblue;
}

Sass的用法

https://www.psvmc.cn/article/2024-07-25-sass-use.html