当前位置:   article > 正文

Vue3+TS教程_vue3 ts

vue3 ts

Vue3

组合式API

1.钩子函数steup
  1. 函数的普通用法
  1. <script>
  2. export default {
  3. setup() {return {}}
  4. }
  5. </script>
  6. <template></template>
  1. 简写使用setup
<script setup></script><template></template>
2.响应式API
  1. ref函数
  1. <script setup>
  2. import { ref } from 'vue'
  3. const state = ref(0)
  4. function increment() {
  5. state.value++
  6. }
  7. </script>
  8. <template>
  9. <button @click="increment">{{ state }}</button>
  10. </template>
  1. reactive函数
  1. <script setup>
  2. import { reactive } from 'vue'
  3. const state = reactive({ count: 0 })
  4. function increment() {
  5. state.count++
  6. }
  7. </script>
  8. <template>
  9. <button @click="increment">{{ state.count }}</button>
  10. </template>
3.计算属性API
  1. 单向响应
  1. <script setup>
  2. import { computed,reactive } from 'vue'
  3. const Person=reactive({X:'张',M:'三'})
  4. Person.XM=computed(()=>{return Person.X+'-'+Person.M})
  5. </script>
  6. <template>
  7. 姓:<input v-model="Person.X">
  8. <br>
  9. 名:<input v-model="Person.M">
  10. <br>
  11. 单向响应:<input v-model="Person.XM">
  12. </template>
  1. 双向响应
  1. <script setup>
  2. import { computed,reactive } from 'vue'
  3. const Person=reactive({X:'张',M:'三'})
  4. Person.AXM=computed({
  5. get(){
  6. return Person.X+'-'+Person.M
  7. },
  8. set(value){
  9. const arr=value.split('-')
  10. Person.X=arr[0]
  11. Person.M=arr[1]
  12. }
  13. })
  14. </script>
  15. <template>
  16. 姓:<input v-model="Person.X">
  17. <br>
  18. 名:<input v-model="Person.M">
  19. <br>
  20. 双向响应:<input v-model="Person.AXM">
  21. </template>
4.监听属性API
  1. 监听整个对象
  1. <!-- // 监听整个对象,由于是浅拷贝,他们新旧指向的是通一个对象 -->
  2. <script setup>
  3. import {reactive,watch} from 'vue'
  4. const Person=reactive({
  5. name:'张三',
  6. age:18,
  7. job:{salary:20}
  8. })
  9. watch(Person,(newVal,oldVal)=>{
  10. console.log('用户信息发生了变化',newVal,oldVal);
  11. })
  12. </script>
  13. <template>
  14. <h2>年龄:{{Person.age}}</h2>
  15. <button @click="Person.age++">+1</button>
  16. </template>
  1. 监听对象中单个属性
  1. <!-- 监听对象中单个属性,监听单个属性可以检测到新旧值 -->
  2. <script setup>
  3. import { strict } from "assert";
  4. import { reactive, watch } from "vue";
  5. const Person = reactive({
  6. name: "张三",
  7. age: 18,
  8. job: { salary: 20 },
  9. });
  10. watch(
  11. () => Person.age,
  12. (newVal, oldVal) => {
  13. console.log("用户年龄发生了变化", newVal, oldVal);
  14. }
  15. );
  16. </script>
  17. <template>
  18. <h2>年龄:{{ Person.age }}</h2>
  19. <button @click="Person.age++">+1</button>
  20. </template>
  1. 监听多个对象
  1. <script setup>
  2. import { reactive, watch } from "vue";
  3. const Person = reactive({ name: "张三", age: 18, job: { salary: 20 } });
  4. watch([() => Person.name, () => Person.age], (newValue, oldValue) => {
  5. console.log("person.name或者person.age的值变化了", newValue, oldValue);
  6. });
  7. </script>
  8. <template>
  9. <h2>姓名:{{ Person.name }}</h2>
  10. <button @click="Person.name += '~'">修改</button>
  11. <h2>年龄:{{ Person.age }}</h2>
  12. <button @click="Person.age++">+1</button>
  13. </template >
  1. 监听对象中对象(深度监听)
  1. <!-- 监听对象中对象,必须开启深度监听,一般情况不监听对象 -->
  2. <script setup>
  3. import { reactive, watch } from "vue";
  4. const Person = reactive({ name: "张三", age: 18, job: { salary: 20 } });
  5. watch(
  6. () => Person.job,
  7. (newValue, oldValue) => {
  8. console.log("person.job的值变化了", newValue, oldValue);
  9. },
  10. { deep: true }
  11. );
  12. </script>
  13. <template>
  14. <h2>薪资:{{ Person.job.salary }}K</h2>
  15. <button @click="Person.job.salary++">+1</button>
  16. </template>
5.高级监听API
  1. 基本使用(默认执行一次)
  1. <!-- watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。 -->
  2. <script setup>
  3. import { reactive, watchEffect } from "vue";
  4. const Person = reactive({ name: "张三" });
  5. watchEffect(() => {
  6. Person.name;
  7. console.log("姓名发送了变化:" + Person.name,);
  8. });
  9. </script>
  10. <template>
  11. <h2>姓名:{{ Person.name }}</h2>
  12. <button @click="Person.name += '~'">修改</button>
  13. </template>
  1. 监听御前处理oninvalidate参数
  1. <script setup lang="ts">
  2. import { reactive, watchEffect } from "vue";
  3. const Person = reactive({ name: "张三" });
  4. watchEffect((oninvalidate) => {
  5. oninvalidate(() => {
  6. console.log("before");
  7. });
  8. Person.name;
  9. console.log("姓名发送了变化");
  10. });
  11. </script>
  12. <template>
  13. <h2>姓名:{{ Person.name }}</h2>
  14. <button @click="Person.name += '~'">修改</button>
  15. </template>
  1. 停止监听
  1. <script setup lang="ts">
  2. import { reactive, watchEffect } from "vue";
  3. const Person = reactive({ name: "张三" });
  4. const stop = watchEffect((oninvalidate) => {
  5. oninvalidate(() => {
  6. console.log("before");
  7. });
  8. Person.name;
  9. console.log("姓名发送了变化");
  10. });
  11. </script>
  12. <template>
  13. <h2>姓名:{{ Person.name }}</h2>
  14. <button @click="Person.name += '~'">修改</button
  15. ><button @click="stop">停止</button>
  16. </template>
6.响应式对象解构API
  1. toRef函数
  1. <script setup>
  2. import { reactive, toRef } from "vue";
  3. const person = reactive({ A: 1, B: 2 });
  4. const A = toRef(person, "A");
  5. </script><template>
  6. <h2>姓名:{{ A }}</h2>
  7. <button @click="person.A += '~'">修改</button>
  8. </template>
  1. toRefs
  1. <script setup lang="ts">
  2. import { reactive, toRefs } from "vue";
  3. const person = reactive({ A: 1, B: 2 });
  4. const { A, B } = toRefs(person);
  5. </script>
  6. <template>
  7. <h2>姓名:{{ A }}</h2>
  8. <button @click="A += 1">修改</button>
  9. </template>
7.生命周期API
  1. <script setup>
  2. import {
  3. onBeforeMount,
  4. onMounted,
  5. onBeforeUpdate,
  6. onUpdated,
  7. onBeforeUnmount,
  8. onUnmounted,
  9. ref,
  10. } from "vue";
  11. onBeforeMount(() => {
  12. console.log("---挂载之前---");
  13. });
  14. onMounted(() => {
  15. console.log("---挂载---");
  16. });
  17. onBeforeUpdate(() => {
  18. console.log("---更新之前---");
  19. });
  20. onUpdated(() => {
  21. console.log("---更新---");
  22. });
  23. onBeforeUnmount(() => {
  24. console.log("---卸载之前---");
  25. });
  26. onUnmounted(() => {
  27. console.log("---卸载---");
  28. });
  29. </script>
8.ref获取dom
  1. <template>
  2. <div><div ref="box">我是div</div></div>
  3. </template><script>
  4. import { ref, onMounted } from "vue";
  5. export default {
  6. setup() {
  7. let box = ref(null);
  8. //本质是reactive({value:null})
  9. //需要在生命周期获取
  10. onMounted(() => {
  11. // 当界面挂载出来后就会自动执行
  12. console.log(box.value);
  13. });
  14. //接受的是null,原因是setup执行时机比mounted早,dom还没形成
  15. console.log(box.value);
  16. return { box };
  17. },
  18. };
  19. </script>
9.Hooks

(1)官方hooks

  1. useAttrs()
  1. <!-- 父组件 -->
  2. <template><Acom a="456" title="789" /></template>
  3. <!-- 子组件 -->
  4. <!-- 获取父组件传过来的全部参数 -->
  5. <script setup lang="ts">
  6. import { useAttrs } from "vue";
  7. let attr = useAttrs();
  8. console.log(attr);
  9. </script>

(2)自定hooks

  1. 自定义hooks转换图片
  1. import { onMounted } from "vue";
  2. type Options = {
  3. el: string;
  4. };
  5. export default function (options: Options): Promise<{ baseUrl: string }> {
  6. return new Promise((resolve) => {
  7. onMounted(() => {
  8. const img: HTMLImageElement = document.querySelector(
  9. options.el
  10. ) as HTMLImageElement;
  11. img.onload = () => {
  12. resolve({ baseUrl: base64(img) });
  13. };
  14. });
  15. const base64 = (el: HTMLImageElement) => {
  16. const canvas = document.createElement("canvas");
  17. const ctx = canvas.getContext("2d");
  18. canvas.width = el.widthcanvas.height = el.heightctx?.drawImage(
  19. el,
  20. 0,
  21. 0,
  22. canvas.width,
  23. canvas.height
  24. );
  25. return canvas.toDataURL("image/jpg");
  26. };
  27. });
  28. }
  1. 使用hooks
  1. <script setup lang="ts">
  2. import BASE64 from './hooks'
  3. BASE64({ el: '#img' }).then(resolve => {console.log(resolve.baseUrl)
  4. })
  5. </script>

(3)第三方hooks

  1. 安装依赖yarn add @vueuse/core
  2. 简单使用
  1. <script setup lang="ts">
  2. import { ref } from "vue";
  3. import { useDraggable } from "@vueuse/core";
  4. const el = ref<HTMLElement | null>(null); // `style` will be a helper computed for `left: ?px; top: ?px;`
  5. const { x, y, style } = useDraggable(el, { initialValue: { x: 40, y: 40 } });
  6. </script>
  7. <template>
  8. <div ref="el" :style="style" style="position: fixed">
  9. Drag me! I am at {{ x }}, {{ y }}
  10. </div>
  11. </template>

组件间通讯

1.props父传子
  1. 父组件
  1. <script setup >
  2. import HelloWorld from './components/HelloWorld.vue'
  3. </script>
  4. <template>
  5. <HelloWorld msg="1"/>
  6. </template>
  1. 子组件
  1. <script setup lange="ts">
  2. // const props=defineProps(['msg'])
  3. //const props=defineProps({msg:String})
  4. const props=withDefaults(defineProps<{msg: string}>(), {
  5. msg: ''
  6. });
  7. console.log(props.msg)
  8. </script>
2.emit子传父
  1. 父组件
  1. <script setup >
  2. import HelloWorld from './components/HelloWorld.vue'
  3. const getuser=(a)=>{
  4. console.log(a)
  5. }
  6. </script>
  7. <template>
  8. <HelloWorld @getuser="getuser"/>
  9. </template>
  1. 子组件
  1. <script setup lang="ts">
  2. const emit = defineEmits(['getuser'])
  3. function buttonClick() {
  4. emit('getuser',1)
  5. }
  6. </script>
  7. <template>
  8. <button @click="buttonClick">传输</button>
  9. </template>
  1. 自定义事件事件校检
  1. <script setup>
  2. const emit = defineEmits({
  3. // 没有校验click: null,
  4. // 校验 submit 事件
  5. submit: ({ email, password }) => {
  6. if (email && password) {
  7. return true
  8. } else {
  9. console.warn('Invalid submit event payload!')
  10. return false
  11. }
  12. }
  13. })
  14. function submitForm(email, password) {
  15. emit('submit', { email, password })
  16. }
  17. </script>
3.插槽通讯

(1)匿名插槽

  1. 子组件
  1. <template>
  2. <!-- slot插槽占位 -->
  3. <slot></slot>
  4. </template>
  1. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from "./components/HelloWorld.vue";
  3. </script>
  4. <template>
  5. <HelloWorld>插槽传递</HelloWorld>
  6. </template>

(2)具名插槽

  1. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from "./components/HelloWorld.vue";
  3. </script>
  4. <template>
  5. <HelloWorld>
  6. <!-- v-slot:简写# -->
  7. <template v-slot:btn>
  8. <button>具名插槽</button>
  9. </template>
  10. </HelloWorld>
  11. </template>
  1. 子组件
  1. <template>
  2. <!-- slot插槽占位 -->
  3. <slot name="btn"></slot>
  4. </template>

(3)作用域插槽

  1. 理解:数据在子组件的自身,但根据数据生成的结构需要父组件决定。
  2. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from "./components/HelloWorld.vue";
  3. const person = [
  4. { name: "小明", age: 18 },
  5. { name: "小红", age: 20 },
  6. ];
  7. </script>
  8. <template>
  9. <!-- 父组件将信息传递给子组件 -->
  10. <HelloWorld :person="person">
  11. <!-- 子组件接收父组件的插槽中传的值 -->
  12. <template #tab="scope">
  13. <tr v-for="(item, index) in scope.person" :key="index">
  14. <th>{{ item.name }}</th>
  15. <th>{{ item.age }}</th>
  16. <th><button>编辑</button></th>
  17. </tr>
  18. </template>
  19. </HelloWorld>
  20. </template>
  1. 子组件
  1. <script setup lang="ts">
  2. const props = defineProps<{ person: { name: string, age: number }[] }>()
  3. </script>
  4. <template>
  5. <table border="1">
  6. <tr>
  7. <th>姓名 </th>
  8. <th>年龄</th>
  9. <th>操作 </th>
  10. </tr>
  11. <!--作用域插槽命名 -->
  12. <!-- // 向作用插槽中传值 -->
  13. <slot name="tab" :person="props.person">
  14. </slot>
  15. </table>
  16. </template>
4.依赖注入
  1. 父组件(祖先组件)
  1. <!-- 依赖注入传的参可以在子组件中改变 -->
  2. <template>
  3. <div class="App"><button>我是App</button><A></A></div>
  4. </template>
  5. <script setup lang="ts">
  6. import { provide, ref } from 'vue'
  7. import A from './components/Acom.vue'
  8. let flag = ref<number>(1)
  9. provide('flag', flag)
  10. </script>
  1. 子组件(后代组件)
  1. <template>
  2. <div>我是B<div>{{ flag }}</div><button @click="flag++">+1</button></div>
  3. </template>
  4. <script setup lang="ts">
  5. import { inject, ref } from 'vue'
  6. // 注入值,默认值(让其可以进行类型推断)
  7. const flag = inject('flag', ref(1))
  8. </script>
5.兄弟传参(不推荐)

(1)父组件当成一个桥梁

(2)发布订阅模式

  1. Bus传递
  1. type BusClass = {
  2. emit: (name: string) => void,
  3. on: (name: string, callback: Function) => void
  4. }
  5. type PramsKey = string | number | symbol
  6. type List = {
  7. [key: PramsKey]: Array<Function>
  8. }
  9. class Bus implements BusClass {
  10. list: Listconstructor = () => {
  11. this.list = {}
  12. }
  13. emit(name: string, ...args: Array<any>) {
  14. const evnentName: Array<Function> = this.list[name]
  15. evnentName.forEach(fn => {
  16. fn.apply(this, args)
  17. })
  18. }
  19. on(name: string, callback: Function) {
  20. const fn: Array<Function> = this.list[name] || []
  21. fn.push(callback)
  22. this.list[name] = fn
  23. }
  24. }
  25. export default new Bus()
  1. A组件传递数值
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import Bus from '../utils/Bus'
  4. const flag = ref(1)
  5. const Pass = () => {
  6. Bus.emit('pass', flag)
  7. }
  8. </script>
  9. <template>
  10. <div>我是A<div>{{ flag }}</div><button @click="Pass">Pass</button></div>
  11. </template>
  12. <style scoped lang="less"></style>
  1. B组件接收数值
  1. <script setup lang="ts">
  2. import Bus from '../utils/Bus'
  3. import { ref, type Ref } from 'vue'const flag = ref(0)
  4. Bus.on('pass', (Flag: Ref<number>) => {
  5. console.log(Flag)
  6. flag.value = Flag.value
  7. })
  8. </script>
  9. <template>
  10. <div>我是B <div> {{ flag }}</div><button @click="flag++">+</button> </div>
  11. <style scoped lang="less"> </style>
  12. </template>

(3)第三方库mitt

  1. 安装yarn add mitt
  2. 全局挂载mit
  1. <script setup lang="ts">
  2. import { createApp } from 'vue'
  3. import { createPinia } from 'pinia'
  4. import App from './App.vue'
  5. import './assets/main.css'
  6. import mitt from 'mitt'
  7. const Mit = mitt()
  8. const app = createApp(App)// 类型声明
  9. declare module 'vue' {
  10. export interface ComponentCustomProperties { $Bus: typeof Mit }
  11. }
  12. app.use(createPinia())
  13. app.config.globalProperties.$Bus = Mit
  14. app.mount('#app')
  15. </script>
  16. <template>
  17. <div>我是B <div> {{ flag }}</div><button @click="flag++">+</button> </div>
  18. <style scoped lang="less"> </style>
  19. </template>
  1. A组件传递数值
  1. <script setup lang="ts">
  2. import { getCurrentInstance, ref } from 'vue'
  3. const instance = getCurrentInstance()
  4. const flag = ref(1)
  5. const Pass = () => {
  6. instance?.proxy?.$Bus.emit('pass', flag)
  7. }
  8. </script>
  9. <template>
  10. <div>我是A
  11. <div> {{ flag }}</div>
  12. <button @click="Pass">Pass</button>
  13. </div>
  14. <style scoped lang="less"> </style>
  15. </template>
  1. B组件接收数值
  1. <script setup lang="ts">
  2. import { getCurrentInstance, ref, type Ref } from 'vue'const instance = getCurrentInstance()
  3. const flag = ref(0)
  4. instance?.proxy?.$Bus.on('pass', Flag => {
  5. flag.value = (Flag as Ref<number>).value
  6. })
  7. </script>
  8. <template>
  9. <div>我是B<div>{{ flag }}</div><button @click="flag++">+</button></div>
  10. </template>
  11. <style scoped lang="less"></style>
  1. *监听事件
  1. <script setup lang="ts">
  2. import { getCurrentInstance, ref, type Ref } from 'vue'
  3. const instance = getCurrentInstance()
  4. const flag = ref(0)
  5. /*** type:事件名称* Flag:传递参数*/
  6. instance?.proxy?.$Bus.on('*', (type, Flag) => {flag.value = (Flag as Ref<number>).value
  7. })
  8. </script>
  1. 取消监听事件
  1. <script setup lang="ts">
  2. import { getCurrentInstance, ref, type Ref } from 'vue'const instance = getCurrentInstance()
  3. const flag = ref(0)
  4. instance?.proxy?.$Bus.off('pass', Flag => {flag.value = (Flag as Ref<number>).value
  5. })
  6. </script>
  1. 取消全部监听事件
  1. <script setup lang="ts">
  2. import { getCurrentInstance, ref, } from 'vue'
  3. const instance = getCurrentInstance()instance?.proxy?.$Bus.all.clear()
  4. </script>

Typescript的支持

1.全局接口的抽取
  1. src下定义types文件夹命名xx.d.ts
  2. 建立Person接口person.d.ts
  1. interface personInterface{
  2. name:string,
  3. age:number
  4. }
  1. 组件中直接使用
  1. <script setup lang="ts">
  2. const props=defineProps<{
  3. person:personInterface[]
  4. }>()
  5. </script>
  1. 如果不是在src下或src文件下的xx.d.ts文件则需要在tsconfig.json中配置
  1. {
  2. {
  3. ...
  4. },
  5. "include": [
  6. "src/**/*.ts",
  7. "src/**/*.d.ts",
  8. "src/**/*.tsx",
  9. "src/**/*.vue"
  10. ], //配置全局目录"references": [{ "path": "./tsconfig.node.json" }]
  11. }
2.类型增强
  1. 使用环境:全局定义的数据,函数在vue组件中直接访问报错
  2. index.html中定义数据
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>...</head>
  4. <script>
  5. const global=1
  6. </script>
  7. <body>...</body>
  8. </html>
  1. 定义类型增强
  1. // common.d.ts
  2. declare const global:string;
  1. 组件中直接读取
  1. <script setup lang="ts">
  2. console.log(global)
  3. </script>
3.第三方库类型声明
  1. 安装一个库
  2. 安装库的ts类型声明@types/xxxx
4.props组件通讯TS
  1. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from './components/HelloWorld.vue'
  3. </script>
  4. <template>
  5. <HelloWorld msg="1"/>
  6. </template>
  1. 子组件
  1. <script setup lang="ts">
  2. interface msgIterface{
  3. msg:string
  4. }
  5. const props = withDefaults(defineProps<msgIterface>(),{msg:'默认值'})
  6. console.log(props.msg)
  7. </script>
5.emit组件通讯TS
  1. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from './components/HelloWorld.vue'
  3. const getuser=(a:number)=>{
  4. console.log(a)
  5. }
  6. </script>
  7. <template>
  8. <HelloWorld @getuser="getuser"/>
  9. </template>
  10. <style scoped>
  11. </style>
  1. 子组件
  1. <script setup lang="ts">
  2. const emit = defineEmits<{(e: 'getuser', id: number): void}>()
  3. // (e: 事件名, 键名:类型): void
  4. function buttonClick() {
  5. emit('getuser',1)
  6. }
  7. </script>
  8. <template>
  9. <button @click="buttonClick">传输</button>
  10. </template>
  11. <style scoped></style>
6.依赖注入类型推断
  1. 父组件(祖先组件)
  1. <template>
  2. <div class="App"><button>我是App</button><A></A></div>
  3. </template>
  4. <script setup lang="ts">
  5. import { provide, ref } from 'vue'
  6. import A from './components/Acom.vue'
  7. let flag = ref<number>(1)
  8. provide('flag', flag)
  9. </script>
  1. 子组件(后代组件)
  1. <template>
  2. <div>我是B
  3. <div>{{ flag }}</div>
  4. <button @click="flag++">+1</button>
  5. </div>
  6. </template>
  7. <script setup lang="ts">
  8. import { inject, ref , type Ref} from 'vue'
  9. // 注入值,默认值(让其可以进行类型推断)
  10. const flag<Ref<number>> = inject('flag', ref(1))
  11. </script>
7.定义全局函数和全局函数的类型支持
  1. import { createApp } from 'vue'
  2. ...
  3. const app = createApp(App)
  4. type Fileter = {
  5. format: <T>(str: T) => string
  6. }
  7. declare module '@vue/runtime-core'
  8. {
  9. export interface ComponentCustomProperties {$filters: Fileter$env: string}
  10. }
  11. // 全局函数
  12. app.config.globalProperties.$filters = {
  13. format<T>(str: T): string
  14. { return `真${str}`}
  15. }
  16. // 全局变量
  17. app.config.globalProperties.$env = '全局变量'
  18. ...

脚手架Vite

1.基本使用
  1. 创建vue3的项目yarn create vite || npm init vite@latest
  2. 安装插件Volar
2.配置项目路径
  1. tsconfig.json中添加
  1. // 让ts可以识别这个路径
  2. {
  3. "compilerOptions": {
  4. ...
  5. "baseUrl": "./",
  6. "paths": {
  7. "@/*":["src/*"]
  8. }
  9. },
  10. ...
  11. }
  1. vite.config.ts中添加
  1. // https://vitejs.dev/config/
  2. export default defineConfig({
  3. plugins: [vue()],
  4. resolve:{
  5. alias:{"@":join(__dirname,'src')}
  6. }
  7. })
3.eslint和prettierrc的配置
  1. .prettierrc.json
  1. {
  2. "arrowParens": "always",
  3. "bracketSameLine": true,
  4. "bracketSpacing": true,
  5. "embeddedLanguageFormatting": "auto",
  6. "htmlWhitespaceSensitivity": "css",
  7. "insertPragma": false,
  8. "jsxSingleQuote": false,
  9. "printWidth": 120,
  10. "proseWrap": "never",
  11. "quoteProps": "as-needed",
  12. "requirePragma": false,
  13. "semi": false,
  14. "singleQuote": true,
  15. "tabWidth": 2,
  16. "trailingComma": "all",
  17. "useTabs": false,
  18. "vueIndentScriptAndStyle": false,
  19. "singleAttributePerLine": false
  20. }
  1. .eslintrc.cjs
  1. /* eslint-env node */
  2. require('@rushstack/eslint-patch/modern-module-resolution')
  3. module.exports = {
  4. root: true,
  5. extends: ['plugin:vue/vue3-essential',
  6. 'eslint:recommended',
  7. '@vue/eslint-config-typescript',
  8. '@vue/eslint-config-prettier'],
  9. rules: {
  10. 'vue/multi-word-component-names': 'off', // 关闭命名semi: 0 // 结尾无分号
  11. },
  12. parserOptions: {ecmaVersion: 'latest'}
  13. }
4.vite环境变量的配置
  1. vite的环境在import中
  1. <script setup lang="ts">
  2. console.log(import.meta.env)
  3. </script>
  1. 创建.env.development .env.production
  2. package.json中配置运行生产环境,会自动注入
{..."scripts": {"dev": "vite --mode development",...},}
  1. vite.config.ts中读取环境变量
  1. import { fileURLToPath, URL } from 'node:url'
  2. import { defineConfig, loadEnv } from 'vite'
  3. import unocss from 'unocss/vite'
  4. import vue from '@vitejs/plugin-vue'
  5. import { presetIcons, presetAttributify, presetUno } from 'unocss'// https://vitejs.dev/config/
  6. export default ({ mode }: any) => {
  7. // 读取环境变量
  8. console.log(loadEnv(mode, process.cwd()))
  9. return defineConfig({
  10. plugins: [vue()],
  11. resolve: {
  12. alias: {
  13. '@': fileURLToPath(new URL('./src', import.meta.url))
  14. }
  15. }
  16. })
  17. }
  1. 找不到模块“./App.vue”或其相应的类型声明
  1. declare module '*.vue'
  2. {
  3. import type { DefineComponent } from 'vue'
  4. //eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban- typesconst
  5. component: DefineComponent<{}, {}, any>
  6. export default component
  7. }
  1. 类型“ImportMeta”上不存在属性“env”
  1. // tsconfig.json
  2. {
  3. ...
  4. "compilerOptions": {
  5. ...
  6. "types": [ "vite/client" ],
  7. },
  8. ...
  9. }

指令的重构

1.v-model指令

(1)v-model实现组件间数据双向绑定

  1. 父组件
  1. <script setup lang="ts">
  2. import HelloWorld from "./components/HelloWorld.vue";
  3. import { ref } from "vue";
  4. const num=ref(1)
  5. </script>
  6. <template>
  7. <HelloWorld v-model="num"/>
  8. </template>
  1. 子组件
  1. <script setup lang="ts">
  2. import { computed } from 'vue';
  3. const props=defineProps<{modelValue:number}>()
  4. const emit = defineEmits<{(e: 'update:modelValue', id: number): void}>()
  5. // 计算属性实现修改数据的同步
  6. const value=computed({
  7. get(){
  8. return +props.modelValue
  9. },
  10. set(value){
  11. emit('update:modelValue',+value)
  12. }
  13. })
  14. </script>
  15. <template>
  16. <input type="text" v-model="value">
  17. </template>
  1. v-model的原理
  1. <template>
  2. <!-- <HelloWorld v-model="num"/> -->
  3. <HelloWorld :modelValue="num" @update:modelValue="num = $event"/>
  4. </template>

(2)v-model传递特定的名称

  1. 父组件
  1. <script setup lang="ts">
  2. import { ref } from "vue";
  3. import HelloWorld from "./components/HelloWorld.vue";
  4. const num=ref(1)
  5. </script>
  6. <template>
  7. <!-- <HelloWorld :num="num @update:="num = $event""/> -->
  8. <HelloWorld v-model:num="num"/>
  9. </template>
  1. 子组件
  1. <script setup lang="ts">
  2. import { computed } from 'vue';
  3. const props=defineProps<{num:number}>()
  4. const emit = defineEmits<{(e: 'update:num', id: number): void}>()
  5. const value=computed({
  6. get(){return +props.num},
  7. set(value){emit('update:num',+value)}
  8. })
  9. </script>
  10. <template>
  11. <input type="text" v-model="value">
  12. </template>
2.自定义指令

(1)自定义指令的简单使用

  1. 全局自定义指令
  1. // mian.ts
  2. import { createApp } from 'vue'
  3. import './style.css'
  4. import App from './App.vue'
  5. const app=createApp(App)
  6. app.directive('focus',{
  7. mounted(el){el.focus()}
  8. })
  9. app.mount('#app')
  1. 使用自定义指令
  1. <template>
  2. <input type="text" v-model="value" v-focus>
  3. </template>
  1. 局部自定义指令
  1. <script setup>
  2. // 在模板中启用 v-focus
  3. const vFocus = {mounted: (el) => el.focus()
  4. }
  5. </script>
  6. <template>
  7. <input v-focus />
  8. </template>

(2)自定义指令详解

  1. 自定义指令的生命周期
  1. <script setup lang="ts">
  2. import type { Directive, DirectiveBinding } from 'vue'
  3. type Dir = { background: string }
  4. const vMove: Directive = {
  5. created() {}, //元素初始化的时候
  6. beforeMount() {}, //指令绑定到元素后调用 只调用一次
  7. mounted(el: HTMLElement, dir: DirectiveBinding<Dir>) {
  8. console.log(dir.value.background)
  9. el.style.background = dir.value.background
  10. },//元素插入父级dom调用
  11. beforeUpdate() {},//元素被更新之前调用
  12. updated() {}, //元素被更新时调用
  13. beforeUnmount() {}, //在元素被移除前调用
  14. unmounted() {} //指令被移除后调用 只调用一次
  15. }
  16. </script>
  17. <template>
  18. <!-- 自定义指令,参数,修饰符 -->
  19. <div v-move:a.x="{ background: 'red' }">自定义指令</div>
  20. </template>
  21. <style scoped lang="less"></style>
  1. 生命周期的简写
  1. <script setup lang="ts">
  2. import type { Directive, DirectiveBinding } from 'vue'
  3. type Dir = { background: string }
  4. const vMove: Directive = (el: HTMLElement, dir: DirectiveBinding<Dir>) => {
  5. el.style.background = dir.value.background
  6. }
  7. </script>
  8. <template>
  9. <!-- 自定义指令,参数,修饰符 -->
  10. <div v-move:a.x="{ background: 'red' }">自定义指令</div>
  11. </template>
  12. <style scoped lang="less"></style>
  1. 自定义拖拽指令
  1. <script setup lang="ts">
  2. import type { Directive } from 'vue'
  3. const vMove: Directive = (el: HTMLElement) => {
  4. const move = (e: MouseEvent) => {
  5. console.log(e)
  6. el.style.left = e.clientX + 'px'
  7. el.style.top = e.clientY + 'px'
  8. }
  9. // 鼠标按下
  10. el.addEventListener('mousedown', () => {
  11. // 鼠标按下拖拽
  12. document.addEventListener('mousemove', move)
  13. // 鼠标松开
  14. document.addEventListener('mouseup', () => {
  15. // 清除事件
  16. document.removeEventListener('mousemove', move)
  17. })
  18. })
  19. }
  20. </script>
  21. <template>
  22. <!-- 自定义指令,参数,修饰符 -->
  23. <div v-move style="background-color: red;width: 200px;height: 200px;position: fixed;left: 50%;top: 50%;transform: translate(-50%, -50%);">
  24. <div style="background-color: black; width: 200px; color: white">自定义指令</div>
  25. </div>
  26. </template>

响应式原理

1.了解Proxy
  1. Proxy代理的get方法
  1. <script>
  2. let obj={ name:'Vue', age:8 }
  3. let obj2=new Proxy(obj,{
  4. /**target表示obj这个对象*property表示读取的属性的key*/
  5. get(target,property){
  6. console.log('执行了get');
  7. return target[property]
  8. }
  9. })
  10. console.log(obj2.age)
  11. </script>
  1. Proxy代理的set方法
  1. <script>
  2. let obj={name:'Vue',age:8}
  3. let obj2=new Proxy(obj,{
  4. /**target表示obj这个对象*property表示读取的属性的key*newValue表示设置的值*/
  5. set(target,property,newValue){
  6. console.log('执行了set')
  7. target[property]=newValue
  8. }
  9. })
  10. obj2.age=7
  11. console.log(obj2.age)
  12. </script>
2.了解Object.defineProperty
  1. Object.defineProperty(对象.定义属性,用来为一个对象添加新属性)
  1. <script>
  2. let person = {name:'张三',sex:'男',}
  3. // 为 person对象 传输了一个新属性 “age”,并且设定它的值为 18
  4. Object.defineProperty(person,'age',{value=18})
  5. console.log(person)
  6. </script>
  1. Object.defineProperty属性的可枚举可修改的实现
  1. <script>
  2. let person = {name:'张三',sex:'男',}
  3. // 为 person对象 传输了一个新属性 “age”,并且设定它的值为 18
  4. Object.defineProperty(person,'age',{
  5. enumerable=true
  6. // 可枚举
  7. writable=true
  8. // 可修改
  9. configurable:true
  10. // 可删除
  11. value=18
  12. })
  13. console.log(person)
  14. </script>
  1. Object.defineProperty() 的get()方法
  1. <script>
  2. let person = {name: '张三',sex: '男',}
  3. function Observer(obj) {
  4. const keys = Object.keys(obj)
  5. keys.forEach((key) => {
  6. Object.defineProperty(this,key,{
  7. get() {return obj[key]}
  8. })
  9. })
  10. }
  11. const obs = new Observer(person)
  12. console.log(obs.sex);
  13. </script>
  1. Object.defineProperty() 的set()方法
  1. <script>
  2. let person = { name: '张三', sex: '男', }
  3. function Observer(obj) {
  4. const keys = Object.keys(obj)
  5. keys.forEach((key) => {
  6. Object.defineProperty(this, key, {
  7. set(val) {
  8. console.log('set方法调用了')
  9. obj[key] = val
  10. }
  11. })
  12. })
  13. }
  14. const obs = new Observer(person)
  15. obs.name = 15
  16. </script>
3.Vue双向绑定的实现的对比
  1. Vue3的Proxy实现
  1. <body>
  2. <input type="text" id="ipt">
  3. <p id='op'></p>
  4. <script>
  5. function reactive(obj) {
  6. return new Proxy(obj, {
  7. get(target, property) {
  8. return target[property]
  9. },
  10. set(target, property, newVal) { target[property] = newVal }
  11. })
  12. } let newObj = reactive([1, 2])
  13. console.log(newObj[1])
  14. const ipt = document.querySelector('#ipt')
  15. ipt.value = newObj[1]
  16. document.querySelector('#op').innerHTML = newObj[1]
  17. ipt.addEventListener('input', function (e) {
  18. newObj[1] = e.target.valuedocument.querySelector('#op').innerHTML = newObj[1]
  19. })
  20. </script>
  21. </body>
  1. Vue2的Object.defineProperty实现
  1. <body>
  2. <input type="text" id="ipt">
  3. <p id='op'></p>
  4. <script>
  5. function Observer(obj) {
  6. const keys = Object.keys(obj)
  7. keys.forEach((key) => {
  8. Object.defineProperty(this, key, {
  9. get() {
  10. console.log('get方法被调用了');
  11. return obj[key]
  12. },
  13. set(val) {
  14. console.log('set方法调用了')
  15. obj[key] = val
  16. }
  17. })
  18. })
  19. }
  20. const obs = new Observer([1, 2, 3])
  21. const ipt = document.querySelector('#ipt')
  22. ipt.value = obs[1]
  23. document.querySelector('#op').innerHTML = obs[1]
  24. ipt.addEventListener('input', function (e) {
  25. obs[1] = e.target.valuedocument.querySelector('#op').innerHTML = obs[1]
  26. })
  27. </script>
  28. </body>
  1. 上面的测试,Object.property是可以检测到通过索引改变数组的操作的,而Vue没有实现,Object.defineProperty表示这个锅我不背

内置组件

1.内置组件

(1)Teleport组件

  1. 可以将一个组件内部的一部分模板“传送”到该组件的 DOM 结构外层的位置去
  2. 父组件
  1. <!-- 遮罩层组件传送到body下 -->
  2. <script setup lang="ts">
  3. import Acom from './components/Acom.vue'
  4. </script>
  5. <template>
  6. <div class="app"></div>
  7. <Acom />
  8. </template>
  9. <style scoped>
  10. .app {
  11. width: 200px;
  12. height: 200px;
  13. background-color: pink;
  14. }
  15. </style>
  1. 子组件
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. const open = ref(false)
  4. </script>
  5. <template>
  6. <button @click="open=true">显示遮罩层</button>
  7. <!-- 传送到body -->
  8. <Teleport to="body">
  9. <div class="cover" v-show="open">
  10. <span @click="open=false"> X</span>
  11. </div>
  12. </Teleport>
  13. </template>
  14. <style scoped>
  15. .cover {
  16. position: absolute;
  17. z-index: 2;
  18. top: 0;
  19. left: 0;
  20. bottom: 0;
  21. right: 0;
  22. background-color: rgba(0, 0, 0, 0.5);
  23. }
  24. </style>

(2)Transition组件

  1. 非命名动画
  1. <script setup lang="ts">
  2. import { ref } from 'vue';
  3. const show = ref(true)
  4. </script>
  5. <template>
  6. <button @click="show=!show">显示/隐藏</button>
  7. <Transition>
  8. <div class="div" v-if="show"></div>
  9. </Transition>
  10. </template>
  11. <style scoped>
  12. .div {
  13. background-color: pink;
  14. width: 200px;
  15. height: 200px;
  16. margin: auto;
  17. }
  18. .v-enter-active,
  19. .v-leave-active {
  20. transition: opacity 0.5s ease;
  21. }
  22. .v-enter-from,
  23. .v-leave-to {
  24. opacity: 0;
  25. }
  26. </style>
  1. 命名动画
  1. <script setup lang="ts">
  2. import { ref } from 'vue';
  3. const show = ref(true)
  4. </script>
  5. <template>
  6. <button @click="show=!show">显示/隐藏</button>
  7. <Transition name="fade">
  8. <div class="div" v-if="show"></div>
  9. </Transition>
  10. </template>
  11. <style scoped>
  12. .div {
  13. background-color: pink;
  14. width: 200px;
  15. height: 200px;
  16. margin: auto;
  17. }
  18. .fade-enter-active {
  19. transition: all 0.3s ease-out;
  20. }
  21. .fade-leave-active {
  22. transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
  23. }
  24. .fade-enter-from,
  25. .fade-leave-to {
  26. transform: translateX(20px);
  27. opacity: 0;
  28. }
  29. </style>
  1. 过度动画
  1. <Transition mode="out-in">
  2. ...
  3. </Transition>
  1. 结合第三方库Animate.css
  1. <!-- yarn add animate.css -->
  2. <script setup lang="ts">
  3. import { ref } from 'vue'
  4. import 'animate.css'
  5. import Acom from './components/Acom.vue'
  6. const show = ref(true)
  7. </script>
  8. <template>
  9. <transition leave-active-class="animate__animated animate__fadeOut"
  10. enter-active-class="animate__animated animate__fadeIn">
  11. <Acom v-if="show"></Acom>
  12. </transition>
  13. <button @click="show = !show">显示/隐藏</button>
  14. </template>
  15. <style scoped lang="less"></style>
  1. transition 生命周期
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import 'animate.css'
  4. import Acom from './components/Acom.vue'
  5. const show = ref(true)
  6. const beforeEnter = () => {
  7. console.log('进入之前')
  8. }
  9. const enter = (_, done: Function) => {
  10. console.log('过度曲线')
  11. setTimeout(() => { done() }, 3000)
  12. }
  13. const afterEnter = () => {
  14. console.log('过度完成')
  15. }
  16. const enterCancelled = () => {
  17. console.log('进入效果被打断')
  18. }
  19. const beforeLeave = () => {
  20. console.log('离开之前')
  21. }
  22. const leave = (_, done: Function) => {
  23. setTimeout(() => { done() }, 3000)
  24. console.log('过度曲线')
  25. }
  26. const afterLeave = () => {
  27. console.log('离开之后')
  28. }
  29. const leaveCancelled = () => {
  30. console.log('离开效果被打断')
  31. }
  32. </script><template>
  33. <transition leave-active-class="animate__animated
  34. animate__fadeOut" enter-active-class="animate__animated animate__fadeIn" @before-enter="beforeEnter" @enter="enter"
  35. @after-enter="afterEnter" @enter-cancelled="enterCancelled" @before-leave="beforeLeave" @leave="leave"
  36. @after-leave="afterLeave" @leave-cancelled="leaveCancelled">
  37. <Acom v-if="show"></Acom>
  38. </transition>
  39. <button @click="show = !show">显示/隐藏</button>
  40. </template>
  1. 生命周期结合第三方库gsap.js
  1. <!-- yarn add gsap -->
  2. <script setup lang="ts">
  3. import { ref } from 'vue'
  4. import Acom from './components/Acom.vue'
  5. import gsap from 'gsap'
  6. const show = ref(true)// 进入之前
  7. const beforeEnter = (el: Element) => {
  8. gsap.set(el, { width: 0, height: 0 })
  9. }
  10. // 进入过度动画
  11. const enter = (el: Element, done: gsap.Callback) => {
  12. gsap.to(el, { width: 200, height: 200, onComplete: done })
  13. }
  14. // 离开之前
  15. const beforeLeave = (el: Element) => {
  16. gsap.set(el, { width: 200, height: 200 })
  17. }
  18. // 进入过度动画
  19. const leave = (el: Element, done: gsap.Callback) => {
  20. gsap.to(el, { width: 0, height: 0, onComplete: done })
  21. }
  22. </script><template>
  23. <transition@before-enter="beforeEnter"@enter="enter"@before-leave="beforeLeave"@leave="leave">
  24. <Acom v-if="show"></Acom>
  25. </transition>
  26. <button @click="show = !show">显示/隐藏</button>
  27. </template>
  1. 初始化动画
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import Acom from './components/Acom.vue'
  4. const show = ref(true)
  5. </script><template>
  6. <transition appear-from-class="from" appear-active-class="active" appear-to-class="to" appear>
  7. <Acom v-if="show"></Acom>
  8. </transition>
  9. <button @click="show = !show">显示/隐藏</button>
  10. </template>
  11. <style scoped>
  12. .from {
  13. /* 初始化之前 */
  14. width: 0;
  15. height: 0;
  16. }
  17. .active {
  18. /* 过度动画 */
  19. transition: all 2s ease;
  20. }
  21. .to {
  22. /* 初始化完成 */
  23. width: 200px;
  24. height: 200px;
  25. }
  26. </style>
  1. 初始化动画结合Animate.css
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import Acom from './components/Acom.vue'
  4. import 'animate.css'
  5. const show = ref(true)
  6. </script><template>
  7. <transition appear-active-class="animate__animated animate__heartBeat" appear>
  8. <Acom v-if="show"></Acom>
  9. </transition>
  10. <button @click="show = !show">显示/隐藏</button>
  11. </template>
  12. <style scoped></style>

(3)transition-group过度列表

  1. Transition组件无法对v-for的列表进行渲染
  2. transition-group的tag属性
  1. <!-- tag属性可以让transition-group多加一层节点元素 -->
  2. <template>
  3. <div class="wraps">
  4. <transition-group tag="session">
  5. <!-- 使用transition-group渲染的组件要有key-->
  6. <div class="item" v-for="item in 5" :key="item">{{ item }}</div>
  7. </transition-group>
  8. </div>
  9. </template>
  1. 添加列表时的动画效果
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import 'animate.css'
  4. const num = ref(5)
  5. </script><template>
  6. <div class="wraps">
  7. <transition -groupleave-active-class="animate__animated animate__fadeOut"
  8. enter-active-class="animate__animated animate__fadeIn">
  9. <!-- 使用transition-group渲染的组件要有key-->
  10. <div class="item" v-for="item in num" :key="item">{{ item }}</div>
  11. </transition-group>
  12. </div>
  13. <button @click="num++">添加</button><button @click="num--">删除</button>
  14. </template>
  15. <style scoped lang="less">
  16. .wraps {
  17. display: flex;
  18. flex-wrap: wrap;
  19. word-break: break-all;
  20. border: 1px solid #ccc;
  21. .item {
  22. margin: 10px;
  23. }
  24. }
  25. </style>
  1. 平移动画move-class
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import _ from 'lodash'
  4. // 建立9x9数组
  5. let list = ref(Array.apply(null, { length: 81 } as number[]).map((_, index) => { return { id: index, number: (index % 9) + 1 } })
  6. )
  7. // 打乱数组
  8. const random = () => {
  9. list.value = _.shuffle(list.value)
  10. }
  11. console.log(list)
  12. </script><template>
  13. <div><button @click="random">打乱</button>
  14. <transition-group tag="div" class="wraps" move-class="move">
  15. <div v-for="item in list" :key="item.id" class="item">{{ item.number }}</div>
  16. </transition-group>
  17. </div>
  18. </template>
  19. <style scoped lang="less">
  20. .wraps {
  21. display: flex;
  22. flex-wrap: wrap; // 换行
  23. width: calc(25px * 10 + 9px);.item {width: 25px;height: 25px;border: 1px solid #ccc;text-align: center;}
  24. }
  25. .move {
  26. transition: all 1s;
  27. }
  28. </style>
  1. 状态过度(数字过度颜色过度)
  1. <script setup lang="ts">
  2. import { reactive, watch } from 'vue'
  3. import gsap from 'gsap'
  4. const num = reactive({
  5. current: 0, tweenedNumber: 0
  6. })
  7. watch(() => num.current, newVal => {
  8. gsap.to(num, {
  9. duration: 1, // 过度时间tweenedNumber: newVal
  10. })
  11. }
  12. )
  13. </script><template>
  14. <div><input type="text" v-model="num.current" step="20" />
  15. <div>
  16. <!-- 去掉小数点 -->{{ num.tweenedNumber.toFixed(0) }}
  17. </div>
  18. </div>
  19. </template>
  20. <style scoped lang="less"></style>

(4)keep-alive组件

  1. 开启keep-alive 生命周期的变化
  1. 初次进入时: onMounted-> onActivated
  2. 退出后触发: deactivated
  1. 缓存数据
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import Acom from './components/Acom.vue'
  4. const show = ref(true)
  5. </script><template>
  6. <keep-alive>
  7. <Acom v-if="show"></Acom>
  8. </keep-alive>
  9. <button @click="show = !show">显示/隐藏</button>
  10. </template>
  1. include属性和exclude属性
  1. <!-- 注意组件一定要命名才可以使用include -->
  2. <script setup lang="ts">
  3. import { ref } from 'vue'
  4. import Acom from './components/Acom.vue'
  5. import Bcom from './components/Bcom.vue'
  6. const show = ref(true)
  7. </script>
  8. <template>
  9. <keep-alive :include="['Acom']" :exclude="['Bcom']">
  10. <Acom v-if="show"></Acom>
  11. <Bcom v-else></Bcom>
  12. </keep-alive><button @click="show = !show">显示/隐藏</button>
  13. </template>
2.普通组件

(1)全局组件

  1. 配置全局组件
  1. <script setup lang="ts">
  2. import { createApp } from 'vue'
  3. import { createPinia } from 'pinia'
  4. import App from './App.vue'
  5. import Acom from './components/Acom.vue'
  6. import './assets/main.css'
  7. const app = createApp(App)
  8. app.use(createPinia())
  9. app.component('Acom', Acom)
  10. app.mount('#app')
  11. </script>
  1. 使用组件
  1. <template>
  2. <div><Acom></Acom></div>
  3. </template>

(2)异步组件

  1. 子组件中发送了请求变成异步
  1. <script setup lang="ts">
  2. interface ResItf {
  3. code: number
  4. data: {
  5. a: number;
  6. b: number
  7. }[]
  8. message: string
  9. }
  10. let p: Promise<ResItf> = new Promise(resolve => {
  11. setTimeout(() => {}, 3000)
  12. resolve({
  13. code: 0,
  14. data: [{ a: 1, b: 2 },{ a: 11, b: 22 }],
  15. message: ''
  16. })
  17. })
  18. const a = await p
  19. console.log(a)
  20. </script><template><div>异步组件</div><div>异步组件</div><div>异步组件</div>
  21. </template>
  1. 父组件异步调用组件
  1. <script setup lang="ts">
  2. // 异步组件不能这样引入
  3. // import Acom from './components/Acom.vue'
  4. import { defineAsyncComponent } from 'vue'
  5. const Acom = defineAsyncComponent(() => import('./components/Acom.vue'))
  6. </script>
  7. <template>
  8. <div>
  9. <Suspense>
  10. <template #default>
  11. <Acom></Acom>
  12. </template>
  13. <template #fallback> 加载中。。。 </template>
  14. </Suspense>
  15. </div>
  16. </template>
  17. <style scoped lang="less"></style>

语法糖组件命名问题

  1. 安装依赖yarn add vite-plugin-vue-setup-extend
  2. 直接命名
<script lang="ts" setup name="xxx"></script>

常用的CSS的功能

  1. 样式穿透
  1. <style scoped lang="less">
  2. :deep(input) {
  3. color: red;
  4. }
  5. </style>
  1. 插槽选择器
  1. <template>
  2. <div>
  3. <slot name="nums" :nums="['1', '2', '3']"> </slot>
  4. </div>
  5. </template>
  6. <style scoped lang="less">
  7. :slotted(.li) {
  8. color: red;
  9. }
  10. </style>
  1. 全局选择器
  1. <script setup lang="ts"></script>
  2. <template>
  3. <div>
  4. <slot name="nums" :nums="['1', '2', '3']"> </slot>
  5. </div>
  6. </template>
  7. <style scoped lang="less">
  8. :global(.li) {
  9. color: red;
  10. }
  11. </style>
  1. 动态CSS
  1. <script setup lang="ts">
  2. import { reactive } from 'vue'
  3. const style = reactive({
  4. color: 'red'
  5. })
  6. setTimeout(() => {
  7. style.color = 'blue'
  8. }, 3000)
  9. </script><template>
  10. <div class="div">动态css</div>
  11. </template>
  12. <style scoped lang="less">
  13. .div {
  14. color: v-bind('style.color');
  15. }
  16. </style>
1.CSS原子化
  1. 安装unocss yarn add unocss
  2. vite的配置文件中配置
  1. import { fileURLToPath, URL } from 'node:url'
  2. import pxtoViewPort from 'postcss-px-to-viewport'
  3. import { defineConfig } from 'vite'
  4. import unocss from 'unocss/vite'
  5. import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
  6. export default defineConfig({
  7. plugins: [
  8. vue(),
  9. // 配置的原子化
  10. unocss({
  11. rules: [
  12. ['flex', { display: 'flex' }],
  13. ['red', { color: 'red' }],
  14. [/^m-(\d+)$/, ([, d]) => ({ margin: `${Number(d) * 10}px` })
  15. ]
  16. ]
  17. })
  18. ],
  19. resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}}
  20. })
  1. main.ts中引入import 'uno.css'
  2. 其他预设配置中引入
  1. import { fileURLToPath, URL } from 'node:url'
  2. import { defineConfig } from 'vite'
  3. import unocss from 'unocss/vite'
  4. import vue from '@vitejs/plugin-vue'
  5. import { presetIcons, presetAttributify, presetUno } from 'unocss'// https://vitejs.dev/config/
  6. export default defineConfig({
  7. plugins: [vue(), unocss({
  8. // 预设
  9. presets: [presetIcons(), presetAttributify(), presetUno()],
  10. rules: [
  11. ['flex', { display: 'flex' }],
  12. ['red', { color: 'red' }],
  13. [/^m-(\d+)$/, ([, d]) => ({ margin: `${Number(d) * 10}px` })]
  14. ]
  15. })],
  16. resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}}
  17. })
  1. 第一预设图标库
  1. npm i -D @iconify-json/ic
  2. // 后缀ic是选择的图标库
  1. 第二预设属性语义化 无须class
 <div color="red">left</div>
  1. 第三预设
  1. 默认的 @unocss/preset-uno 预设(实验阶段)是一系列流行的原子化框架的 通用超集,
  2. 包括了 Tailwind CSS,Windi CSS,Bootstrap,Tachyons 等。
  3. 例如,ml-3(Tailwind),ms-2(Bootstrap),ma4(Tachyons),mt-10px(Windi CSS)均会生效。
5.Vue3集成Tailwind CSS
  1. 安装依赖yarn add -D tailwindcss@latest postcss@latest autoprefixer@latest
  2. 安装插件tailwind css inteliSence
  3. 生成配置文件npx tailwindcss init -p
  4. tailwind.config.js配置文件中添加
  1. /** @type {import('tailwindcss').Config} */
  2. module.exports = {
  3. content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], theme: { extend: {} }, plugins: []
  4. }
  1. 创建index.css文件并且在mian.ts中引入
  1. @tailwind base;
  2. @tailwind components;
  3. @tailwind utilities;
  1. 使用tailwindcss的样式
  1. <script setup lang="ts"></script>
  2. <template>
  3. <div class="w-screen h-screen bg-red-600 flex justify-center items-center text-8xl text-teal-50">hello tailwind
  4. </div>
  5. </template>
  6. <style scoped lang="less"></style>

面试常用源码

1.app.use()的源码实现
  1. 实现myuse
  1. import type { App } from 'vue'
  2. import { app } from '../main'
  3. interface Use {
  4. install: (app: App, ...options: any[]) => void
  5. }// 插件注册的数组
  6. const installList = new Set()
  7. export function MyUse<T extends Use>(plugin: T, ...options: any[]) {
  8. if (installList.has(plugin)) {
  9. console.log('插件件已经注册')
  10. return
  11. }
  12. plugin.install(app, ...options)
  13. installList.add(plugin)
  14. }
  1. 使用myuse调用插件
  1. import { createApp } from 'vue'
  2. import { createPinia } from 'pinia'
  3. import App from './App.vue'
  4. import './assets/main.css'
  5. import Loading from './components/Loading'
  6. import { MyUse } from './utils/myuse'
  7. export const app = createApp(App)
  8. // 使用插件
  9. // app.use(Loading)
  10. MyUse(Loading)
  11. app.use(createPinia())
  12. app.mount('#app')
  13. type Lod = {
  14. show: () => voidhide: () => void
  15. }
  16. //编写ts loading 声明文件放置报错 和 智能提示
  17. declare module '@vue/runtime-core' {
  18. export interface ComponentCustomProperties { $loading: Lod }
  19. }

移动端适配

1.第一种适配方案

  1. 安装依赖yarn add amfe-flexible postcss postcss-pxtorem@5.1.1
  2. main.ts引入amfe-flexibleimport "amfe-flexible"
  3. 根目录下创建postcss.config.js文件并配置
  1. module.exports = {
  2. plugins: {
  3. 'postcss-pxtorem': {
  4. // 能够把所有元素的px单位转成Rem
  5. // rootValue: 转换px的基准值。
  6. // 编码时, 一个元素宽是75px,则换成rem之后就是2rem
  7. rootValue: 37.5,
  8. propList: ['*']
  9. }
  10. }
  11. }

2.第二种适配方案

  1. 安装依赖yarn add postcss-px-to-viewport -D
  2. vite.config.ts内置postcss.config.js中修改配置
  1. import { fileURLToPath, URL } from 'node:url'
  2. import pxtoViewPort from 'postcss-px-to-viewport'
  3. import { defineConfig } from 'vite'
  4. import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
  5. export default defineConfig({
  6. plugins: [vue()], css: {
  7. postcss: {
  8. plugins: [
  9. //postcss-px-to-viewport的配置
  10. pxtoViewPort({
  11. unitToConvert: 'px', // 要转化的单位
  12. viewportWidth: 750, // UI设计稿的宽度
  13. unitPrecision: 6, // 转换后的精度,即小数点位数
  14. propList: ['*'],// 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
  15. viewportUnit: 'vw', // 指定需要转换成的视窗单位,默认vw
  16. fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位,默认vw
  17. selectorBlackList: ['ignore-'], // 指定不转换为视窗单位的类名
  18. minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
  19. mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
  20. replace: true, // 是否转换后直接更换属性值
  21. landscape: false // 是否处理横屏情况
  22. })
  23. ]
  24. }
  25. },
  26. resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}}
  27. })
  1. 创建postcss-px-to-viewport.d.ts的声明文件
  1. declare module 'postcss-px-to-viewport' {
  2. type Options = {
  3. unitToConvert: 'px' | 'rem' | 'cm' | 'em'
  4. viewportWidth: number
  5. viewportHeight: number // not now used; TODO: need for different units and math for different
  6. propertiesunitPrecision: number
  7. viewportUnit: string
  8. fontViewportUnit: string // vmin is more suitable.
  9. selectorBlackList: string[]
  10. propList: string[]
  11. minPixelValue: number
  12. mediaQuery: boolean
  13. replace: boolean
  14. landscape: boolean
  15. landscapeUnit: string
  16. landscapeWidth: number
  17. }
  18. export default function (options: Partial<Options>): any
  19. }
  1. 在tsconfig.json中引入声明文件
  1. {
  2. "extends": "@vue/tsconfig/tsconfig.web.json",
  3. "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "postcss-px-to-viewport.d.ts"],
  4. "compilerOptions": {
  5. "baseUrl": ".",
  6. "types": ["element-plus/global"],
  7. "paths": { "@/*": ["./src/*"] }
  8. },
  9. "references": [{ "path": "./tsconfig.config.json" }]
  10. }
  1. 注意:如果外面用到了postcss.config.js,在postcss.config.js中添加配置文件
  1. // 要禁用vite.config.ts内置postcss.config.js
  2. module.exports = {
  3. plugins: {
  4. tailwindcss: {},
  5. autoprefixer: {},
  6. 'postcss-px-to-viewport': {
  7. unitToConvert: 'px', // 要转化的单位
  8. viewportWidth: 320, // UI设计稿的宽度//
  9. unitPrecision: 6, // 转换后的精度,即小数点位数//
  10. propList: ['*'], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换//
  11. viewportUnit: 'vw', // 指定需要转换成的视窗单位,默认vw//
  12. fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位,默认vw//
  13. selectorBlackList: ['wrap'], // 指定不转换为视窗单位的类名,//
  14. minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换//
  15. mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false//
  16. replace: true, // 是否转换后直接更换属性值//
  17. exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配//
  18. landscape: false // 是否处理横屏情况
  19. }
  20. }
  21. }

的其他知识点

1.全局函数和全局变量

  1. 全局函数
  1. import { createApp } from 'vue'
  2. import { createPinia } from 'pinia'
  3. import App from './App.vue'
  4. import './assets/main.css'
  5. const app = createApp(App)
  6. type Fileter = {
  7. format: <T>(str: T) => string
  8. }
  9. declare module '@vue/runtime-core' {
  10. export interface ComponentCustomProperties { $filters: Fileter }
  11. }
  12. // 全局函数
  13. app.config.globalProperties.$filters = {
  14. format<T>(str: T): string { return `真${str}` }
  15. }
  16. app.use(createPinia())
  17. app.mount('#app')
  1. 全局变量
  1. import { createApp } from 'vue'
  2. import { createPinia } from 'pinia'
  3. import App from './App.vue'
  4. import './assets/main.css'
  5. const app = createApp(App)
  6. declare module '@vue/runtime-core' {
  7. export interface ComponentCustomProperties {$env: string}
  8. }
  9. // 全局变量
  10. app.config.globalProperties.$env = '全局变量'
  11. app.use(createPinia())
  12. app.mount('#app')

2.自定义插件

  1. 封装插件的样式,抛出插件的显示隐藏方法
  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. const isShow = ref(false)
  4. // 控制load显示
  5. const show = () => {
  6. console.log(111)isShow.value = true
  7. }
  8. const hide = () => {
  9. isShow.value = false
  10. }
  11. // 这里抛出的东西会在插件声明文件中调用
  12. defineExpose({show,hide})
  13. </script>
  14. <template>
  15. <div v-if="isShow" class="loading">loading....</div>
  16. </template>
  17. <style scoped lang="less"></style>
  1. 创建接收调用插件的方法
  1. import { render, type App, type VNode } from 'vue'
  2. import Loading from './index.vue'
  3. import { createVNode } from 'vue'
  4. export default {
  5. install(app: App) {
  6. // 变成div
  7. const Vnode: VNode = createVNode(Loading)
  8. // 挂载
  9. render(Vnode, document.body)
  10. // console.log(app, Vnode)//
  11. // 读取loading组件中导出的方法//
  12. console.log(Vnode.component?.exposed.show)
  13. // 对插件的方法进行全局挂载
  14. app.config.globalProperties.$loading = {
  15. show: Vnode.component?.exposed?.show,
  16. hide: Vnode.component?.exposed?.hide
  17. }
  18. }
  19. }
  1. main.ts中挂载上面的方方法
  1. import { createApp } from 'vue'
  2. import { createPinia } from 'pinia'
  3. import App from './App.vue'
  4. import './assets/main.css'
  5. import Loading from './components/Loading'
  6. const app = createApp(App)
  7. // 使用插件
  8. app.use(Loading)
  9. app.use(createPinia())
  10. app.mount('#app')
  1. 对插件的方法进行声明
  1. type Lod = {
  2. show: () => void
  3. hide: () => void
  4. }
  5. //编写ts loading 声明文件放置报错 和 智能提示
  6. declare module '@vue/runtime-core' {
  7. export interface ComponentCustomProperties {$loading: Lod}
  8. }
  1. 使用插件
  1. <script setup lang="ts">
  2. import { getCurrentInstance } from 'vue'
  3. const instance = getCurrentInstance()
  4. // 调用插件
  5. instance?.proxy?.$loading.show()
  6. // 5秒关闭插件
  7. setTimeout(() => {
  8. instance?.proxy?.$loading.hide()
  9. }, 5000)
  10. </script>
  11. <template>
  12. <div></div>
  13. </template>
  14. <style scoped lang="less"></style>

3.函数式编程

  1. h函数
  1. h 接收三个参数
  2. 1.type 元素的类型
  3. 2.propsOrChildren 数据对象, 这里主要表示(props, attrs, dom props, class 和 style)
  4. 3.children 子节点
  1. h函数的多种组合
  1. // 除类型之外的所有参数都是可选的
  2. h('div')
  3. h('div', { id: 'foo' })//属性和属性都可以在道具中使用
  4. //Vue会自动选择正确的分配方式
  5. h('div', { class: 'bar', innerHTML: 'hello' })
  6. // props modifiers such as .prop and .attr can be added
  7. // with '.' and `^' prefixes respectively
  8. h('div', { '.name': 'some-name', '^width': '100' })// class 和 style 可以是对象或者数组
  9. h('div', { class: [foo, { bar }], style: { color: 'red' } })// 定义事件需要加on 如 onXxx
  10. h('div', { onClick: () => {} })// 子集可以字符串
  11. h('div', { id: 'foo' }, 'hello')//如果没有props是可以省略props 的
  12. h('div', 'hello')
  13. h('div', [h('span', 'hello')])// 子数组可以包含混合的VNode和字符串
  14. h('div', ['hello', h('span', 'hello')])
  1. 使用props传递参数
  1. <template>
  2. <Btn text="按钮"></Btn>
  3. </template>
  4. <script setup lang='ts'>
  5. import { h, } from 'vue';
  6. type Props = {
  7. text: string
  8. }
  9. const Btn = (props: Props, ctx: any) => {
  10. return h('div', {
  11. class: 'p-2.5 text-white bg-green-500 rounded shadow-lg w-20 text-center inline m-1',
  12. },
  13. props.text)
  14. }
  15. </script>
  1. 接收emit
  1. <template>
  2. <Btn @on-click="getNum" text="按钮"></Btn>
  3. </template>
  4. <script setup lang='ts'>
  5. import { h, } from 'vue';
  6. type Props = {
  7. text: string
  8. }
  9. const Btn = (props: Props, ctx: any) => {
  10. return h('div', {
  11. class: 'p-2.5 text-white bg-green-500 rounded shadow-lg w-20 text-center inline m-1',
  12. onClick: () => { ctx.emit('on-click', 123) }
  13. }, props.text)
  14. }
  15. const getNum = (num: number) => {
  16. console.log(num);
  17. }
  18. </script>
  1. 定义插槽
  1. <template>
  2. <Btn @on-click="getNum">
  3. <template #default>按钮slots</template>
  4. </Btn>
  5. </template>
  6. <script setup lang='ts'>
  7. import { h, } from 'vue';
  8. type Props = {
  9. text?: string
  10. }
  11. const Btn = (props: Props, ctx: any) => {
  12. return h('div', {
  13. class: 'p-2.5 text-white bg-green-500 rounded shadow-lg w-20 text-center inline m-1',
  14. onClick: () => { ctx.emit('on-click', 123) }
  15. }, ctx.slots.default())
  16. }
  17. const getNum = (num: number) => {
  18. console.log(num);
  19. }
  20. </script>

4.vue性能优化

(1)跑分和打包体积

  1. 跑分vue开发工具Lighthouse
  1. 从Performance页的表现结果来看,得分37分,并提供了很多的时间信息,
  2. 我们来解释下这些选项代表的意思:FCP (First Contentful Paint):
  3. 首次内容绘制的时间,浏览器第一次绘制DOM相关的内容,也是用户第一次看到页面内容的时间。
  4. Speed Index: 页面各个可见部分的显示平均时间,
  5. 当我们的页面上存在轮播图或者需要从后端获取内容加载时,这个数据会被影响到。
  6. LCP (Largest Contentful Paint):最大内容绘制时间,页面最大的元素绘制完成的时间。
  7. TTI(Time to Interactive):从页面开始渲染到用户可以与页面进行交互的时间,
  8. 内容必须渲染完毕,交互元素绑定的事件已经注册完成。
  9. TBT(Total Blocking Time):记录了首次内容绘制到用户可交互之间的时间,
  10. 这段时间内,主进程被阻塞,会阻碍用户的交互,页面点击无反应。
  11. CLS(Cumulative Layout Shift):计算布局偏移值得分,会比较两次渲染帧的内容偏移情况,
  12. 可能导致用户想点击A按钮,但下一帧中,A按钮被挤到旁边,导致用户实际点击了B按钮。
  1. 打包后rollup的插件yarn add rollup-plugin-visualizer
  1. import { fileURLToPath, URL } from 'node:url'
  2. import { defineConfig, loadEnv } from 'vite'
  3. import unocss from 'unocss/vite'
  4. import vue from '@vitejs/plugin-vue'
  5. import { visualizer } from 'rollup-plugin-visualizer'// https://vitejs.dev/config/
  6. export default ({ mode }: any) => {
  7. console.log(loadEnv(mode, process.cwd()))
  8. return defineConfig({
  9. plugins: [
  10. vue(), // 配置rollup的插件
  11. visualizer({ open: true })
  12. ],
  13. resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }
  14. })
  15. }
  1. vite配置文件中vite的优化
  1. import { fileURLToPath, URL } from "node:url";
  2. import { defineConfig } from "vite";
  3. import vue from "@vitejs/plugin-vue";
  4. import vueJsx from "@vitejs/plugin-vue-jsx";// https://vitejs.dev/config/
  5. export default defineConfig({
  6. ...
  7. build: {
  8. chunkSizeWarningLimit: 2000,
  9. cssCodeSplit: true, //css 拆分
  10. sourcemap: false, //不生成sourcemap
  11. minify: 'terser', //是否禁用最小化混淆,esbuild打包速度最快,terser打包体积最小。
  12. assetsInlineLimit: 5000 //小于该值 图片将打包成Base64
  13. }
  14. })

(2)PWA离线存储技术

  1. 安装依赖yarn add vite-plugin-pwa -D
  2. 配置
  1. import { fileURLToPath, URL } from "node:url";
  2. import { VitePWA } from "vite-plugin-pwa";
  3. import { defineConfig } from "vite";
  4. import vue from "@vitejs/plugin-vue";
  5. import vueJsx from "@vitejs/plugin-vue-jsx";// https://vitejs.dev/config/
  6. export default defineConfig({
  7. plugins: [vue(), vueJsx(), VitePWA({
  8. workbox: {
  9. cacheId: "key", //缓存名称
  10. runtimeCaching: [{
  11. urlPattern: /.*\.js.*/, //缓存文件
  12. handler: "StaleWhileRevalidate", //重新验证时失效
  13. options: {
  14. cacheName: "XiaoMan-js", //缓存js,名称
  15. expiration: {
  16. maxEntries: 30, //缓存文件数量 LRU算法
  17. maxAgeSeconds: 30 * 24 * 60 * 60, //缓存有效期
  18. },
  19. },
  20. }],
  21. },
  22. })],
  23. ...
  24. });

(3)其他性能优化

  1. 图片懒加载
  1. import { createApp } from 'vue'
  2. import App from './app'
  3. import lazyPlugin from 'vue3-lazy'
  4. const app = createApp(App)
  5. app.use(lazyPlugin, {loading: 'loading.png',error: 'error.png'})
  6. app.mount('#app')
  7. <img v-lazy="user.avatar" >
  1. 虚拟列表实现
  1. 后台返回多数据
  2. 展示可视区的dom
  1. 多线程 使用 new Worker 创建
  1. // worker脚本与主进程的脚本必须遵守同源限制。他们所在的路径协议、域名、端口号三者需要相同
  2. const myWorker1 = new Worker("./calcBox.js");
  3. // 都使用postMessage发送消息
  4. worker.postMessage(arrayBuffer, [arrayBuffer]);
  5. // 都使用onmessage接收消息
  6. self.onmessage = function (e) {
  7. // xxx这里是worker脚本的内容
  8. };
  9. 关闭worker.terminate();
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/859998
推荐阅读
相关标签
  

闽ICP备14008679号