封装代码片段
- 通过生成配置项代码网站生成现成的片段,附vue3+ts;
- vscode => 文件 => 首选项 => 配置代码片段 => vue.json,插入代码片段代码;
- 在vscode中输入tsvue即可
vue3+ts代码片段:
"my vue3 ts": {
"prefix": "tsvue",
"body": [
"<script setup lang=\"ts\">",
"import { ref, onMounted } from 'vue'",
"",
"onMounted(async() => {})",
"",
"</script>",
"",
"<template>",
" <div class=\"${1:home}\">",
" ${1:home}",
" </div>",
"</template>",
"",
"<style lang=\"less\" scoped>",
".${1:home} {}",
"</style>",
""
],
"description": "my vue3 ts"
}
环境代码
ex:开发和线上后端链接不同时,希望根据不同环境去请求不同接口:
开发:development,线上:production
根目录新建.env
,.env.development
,.env.production
文件
XXX_YYY='xxxxxx'
element-plus
npm install element-plus --save
全局引入
src/main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
部分引入
只考虑自动引入
npm install -D unplugin-vue-components unplugin-auto-import vite-plugin-style-import consola
vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import {
createStyleImportPlugin,
ElementPlusResolve,
} from 'vite-plugin-style-import';
export default defineConfig({
// ...
plugins: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
createStyleImportPlugin({
resolves: [ElementPlusResolve()],
libs: [
{
libraryName: 'element-plus',
esModule: true,
resolveStyle: (name: string) => {
return `element-plus/theme-chalk/${name}.css`;
},
},
],
}),
],
})
其中 vite-plugin-style-import
是引入各类UI的,不止elementUI,需要了解一下链接
清除默认样式
src => assets => base.css
这里就单纯的清除默认css,这仨是一定要清除的,其他的可以等用到的时候清;
html, body, #app {
height: 100%;
margin: 0;
padding: 0;
}
src => assets => main.css
这里是针对于全局去写一些全局样式,使全局样式统一;
@import './base.css';
#app {
width: 100%;
height: 100%;
}
注册全局icon
这里只是注册element icon,实际工作中常见的也有用阿里妈妈的,这里也建议使用阿里妈妈,阿里妈妈icon算是element icon 的超集。src => global => register-icon.ts
import type { App } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
export default function registerIcon(app: App) {
// 注册全局图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
}
src/main.ts
import registerIcons from './global/register-icons'
app.use(registerIcon)
引入子组件类型
import SonComponent from './son-component.vue'
// 直接使用any
const sonComponentRef = ref<any>()
// 使用泛型
const sonComponentRef = ref<InstanceType<typeof SonComponent>>()