2
记录 Vue3 使用过程中的问题和解决方案

Vite

缓存问题

文件系统缓存

Vite 会将预构建的依赖缓存到 node_modules/.vite,但是如果你是库作者,调试中会经常遇到需要频繁刷新缓存的场景。
想要强制 Vite 重新构建依赖,你可以用 --force 命令行选项启动开发服务器,或者手动删除 node_modules/.vite 目录。

这里我选择写入 package.json 中

"scripts": {
  "dev": "vite --force"
},

另外 vite build 似乎也会受到缓存的影响

/src/main

  • 全局属性可以通过 appconfig.globalProperties 绑定
    vue3

    import { 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 中移除,不再支持。

OceanZH
325 声望14 粉丝

前端开发