15 个 Vue3 全家桶开发的避坑经验( 三 )


文章插图
看起来很不直观 。我们都知道,要获取和修改 ref声明的变量的值,需要通过 .value来获取,所以你也可以:
console.log( '[测试 ref]', count.value);
这里还有另一种方式,就是在控制台的设置面板中开启 「 Enable custom formatters」选项 。
image.png

15 个 Vue3 全家桶开发的避坑经验

文章插图
image.png
这时候你会发现,控制台输出的 ref的格式发生变化了:
更加清晰直观了 。
这个方法是我在《Vue.js 设计与实现》中发现的,但在文档也没有找到相关介绍,如果有朋友发现了,欢迎告知~
二、Vite 1. Vite 动态导入的使用问题
文档地址:https://cn.vitejs.dev/guide/features.html#glob-import
使用 webpack 的同学应该都知道,在 webpack 中可以通过 require.context动态导入文件:
// https://webpack.js.org/guides/dependency-management/
require.context( './test', false, /.test.js$/);
在 Vite 中,我们可以使用这两个方法来动态导入文件:
  • import.meta.glob
该方法匹配到的文件默认是 懒加载,通过 动态导入实现,构建时会 分离独立的 chunk,是 异步导入,返回的是 Promise,需要做异步操作,使用方式如下:
constComponents = import.meta.glob( '../components/**/*.vue');
// 转译后:
constComponents = {
'./components/a.vue': => import( './components/a.vue'),
'./components/b.vue': => import( './components/b.vue')
}
  • import.meta.globEager
该方法是 直接导入所有模块,并且是 同步导入,返回结果直接通过 for...in循环就可以操作,使用方式如下:
constComponents = import.meta.globEager( '../components/**/*.vue');
// 转译后:
import* as__glob__0_0 from'./components/a.vue'
import* as__glob__0_1 from'./components/b.vue'
constmodules = {
'./components/a.vue': __glob__0_0,
'./components/b.vue': __glob__0_1
}
如果仅仅使用异步导入 Vue3 组件,也可以直接使用 Vue3 defineAsyncComponent API 来加载:
// https://v3.cn.vuejs.org/api/global-api.html#defineasynccomponent
import{ defineAsyncComponent } from'vue'
constAsyncComp = defineAsyncComponent( =>
import( './components/AsyncComponent.vue')
)
app.component( 'async-component', AsyncComp)
2. Vite 配置 alias 类型别名
文档地址:https://cn.vitejs.dev/config/#resolve-alias
当项目比较复杂的时候,经常需要配置 alias 路径别名来简化一些代码:
importHome from'@/views/Home.vue'
在 Vite 中配置也很简单,只需要在 vite.config.ts的 resolve.alias中配置即可:
// vite.config.ts
exportdefaultdefineConfig({
base: './',
resolve: {
alias: {
"@": path.join(__dirname, "./src")
},
}
// 省略其他配置
})
如果使用的是 Type 时,编辑器会提示路径不存在的警告??,这时候可以在 tsconfig.json中添加 compilerOptions.paths的配置:
{
"compilerOptions": {
"paths": {
"@/*": [ "./src/*"]
}
}
}
3. Vite 配置全局 scss
文档地址:https://cn.vitejs.dev/config/#css-preprocessoroptions
当我们需要使用 scss 配置的主题变量(如 $primary)、mixin方法(如 @mixin lines)等时,如:
< setup lang="ts">
</>
<template>
<div class="container"></div>
</template>
<style scoped lang="scss">
.container{
color: $primary;
@include lines;
}
</style>
我们可以将 scss 主题配置文件,配置在 vite.config.ts的 css.preprocessorOptions.scss.additionalData中:
// vite.config.ts
exportdefaultdefineConfig({
base: './',
css: {
preprocessorOptions: {
// 添加公共样式
scss: {
additionalData: '@import "./src/style/style.scss";'
}
}
},
plugins: [vue]
// 省略其他配置
})
如果不想使用 scss 配置文件,也可以直接写成 scss 代码:
exportdefaultdefineConfig({
css: {


推荐阅读