记录 Vue3 使用过程中的问题和解决方案
Vite
缓存问题
Vite 会将预构建的依赖缓存到node_modules/.vite
,但是如果你是库作者,调试中会经常遇到需要频繁刷新缓存的场景。
想要强制 Vite 重新构建依赖,你可以用--force
命令行选项启动开发服务器,或者手动删除node_modules/.vite
目录。
这里我选择写入 package.json 中
"scripts": {
"dev": "vite --force"
},
另外 vite build
似乎也会受到缓存的影响
/src/main
全局属性可以通过
appconfig.globalProperties
绑定
vue3import { createApp } from 'vue' import axios from 'axios' createApp(App).config.globalProperties.$http = axios
vue2
import Vue from 'vue'; import axios from 'axios' Vue.prototype.$http = axios;
- Augmenting Global Properties
为 globalProperties 扩充类型
如果使用了ts
,在 build 的时候,可能会报如下错误Property '$http' does not exist on type 'CreateComponentPublicInstance<......
这个时候需要在src/shims-vue.d.ts
中补充如下声明,并且确保shims-vue.d.ts
文件被包含在tsconfig.json
中了import axios from 'axios' declare module 'vue' { interface ComponentCustomProperties { $http: typeof axios } }
setup script
- getcurrentinstance
setup
中可以通过getCurrentInstance().proxy
获取类似 Vue2 中this
的引用 - 组合式api中的模板引用
<template>
中对子组件的ref="comp1"
引用,在setup
中可以声明同名变量获取const comp1 = ref(null)
- defineExpose
script setup
组件中需要主动使用defineExpose({...})
暴露想让外部通过ref
引用使用的组件内属性(变量,方法...) - $children
$children
实例 property 已从 Vue 3.0 中移除,不再支持。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。