共计 744 个字符,预计需要花费 2 分钟才能阅读完成。
使用过 Vue3 开发的难免会被每个页面都要引入 vue 的 Api 而烦恼,这也是相较 2.x 版本的最大的区别。有相过为什么要这样做吗?
因为在 2.x 的版本中,我们在入口文件 main 中全局注册唯一的 vue 对象实例,而所有的 api 都可以通过这个对象的引用获得。Vue 3 的改进就是要优化打包的体积,更方便的进行复用逻辑组件,分成一个个的小的 vue 实例,从而 Api 是根据需要手动引入。
于是出现以下这种代码
import {ref, computed, watch} from 'vue'
const counter = ref(0)
const doubled = computed(() => counter.value * 2)
watch(doubled, (v) => {console.log('New value:' + v)
})
如果你想全局引入一次,每个文件都能自由使用 ref, computed, watch… 这些 Api 怎么办?
可以使用 vue-global-api 这个插件
安装
npm i vue-global-api
然后在 main 文件中导入全局注册
// main.js
import 'vue-global-api'
定制化使用
如果担心以下引入所有的 Api 对资源是一种浪费,也可以根据自己的需要对使用到的 Api 进行单独的引入
// only register `ref` and `computed` as global APIs
import 'vue-global-api/ref'
import 'vue-global-api/computed'
在最新的
正文完