// Vue2.x
Vue.prototype.$api = axIOS;
Vue.prototype.$eventBus = eventBus;
// Vue3.x
constApp = createApp({})
app.config.globalProperties.$api = axios;
app.config.globalProperties.$eventBus = eventBus;
使用时需要先通过 vue 提供的 getCurrentInstance方法获取实例对象:
// A.vue
< setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
onMounted( => {
const instance = <any>getCurrentInstance;
const { $api, $eventBus } = instance.appContext.config.globalProperties;
// do something
})
</>
其中 instance内容输出如下:

文章插图
5. v-model 变化
文档地址:https://v3.cn.vuejs.org/guide/migration/v-model.html当我们在使用 v-model指令的时候,实际上 v-bind和 v-on组合的简写,Vue2.x 和 Vue3.x 又存在差异 。
- Vue2.x
<ChildComponent :value=https://www.isolves.com/it/cxkf/qd/2022-08-16/"pageTitle" @input="pageTitle = $event" />
在子组件中,如果要对某一个属性进行双向数据绑定,只要通过 this.$emit('update:myPropName', newValue)就能更新其 v-model绑定的值 。
- Vue3.x
<ChildComponent :modelValue=https://www.isolves.com/it/cxkf/qd/2022-08-16/"pageTitle" @update:modelValue="pageTitle = $event"/>
-setup模式下就不能使用 this.$emit去派发更新事件,毕竟没有 this,这时候需要使用前面有介绍到的 defineProps、defineEmits 两个宏来实现:
// 子组件 child.vue
// 文档:https://v3.cn.vuejs.org/api/sfc--setup.html#defineprops-%E5%92%8C-defineemits
< setup lang="ts">
import { ref, onMounted, watch } from "vue";
const emit = defineEmits(['update:modelValue']); // 定义需要派发的事件名称
let curValue = https://www.isolves.com/it/cxkf/qd/2022-08-16/ref('');
let props = withDefaults(defineProps<{
modelValue: string;
}>, {
modelValue: '',
})
onMounted( => {
// 先将 v-model 传入的 modelValue 保存
curValue.value = https://www.isolves.com/it/cxkf/qd/2022-08-16/props.modelValue;
})
watch(curValue, (newVal, oldVal) => {
// 当 curValue 变化,则通过 emit 派发更新
emit('update:modelValue', newVal)
})
</>
<template>
<div></div>
</template>
<style lang="scss" scoped></style>
父组件使用的时候就很简单:
// 父组件 father.vue
< setup lang="ts">
import { ref, onMounted, watch } from "vue";
let curValue = https://www.isolves.com/it/cxkf/qd/2022-08-16/ref('');
watch(curValue, (newVal, oldVal) => {
console.log('[curValue 发生变化]', newVal)
})
</>
<template>
<Child v-model='curValue'></Child>
</template>
<style lang="scss" scoped></style>
6. 开发环境报错不好排查
文档地址:https://v3.cn.vuejs.org/api/application-config.html#errorhandlerVue3.x 对于一些开发过程中的异常,做了更友好的提示警告,比如下面这个提示:

文章插图
这样能够更清楚的告知异常的出处,可以看出大概是 <ElInput 0=......这边的问题,但还不够清楚 。这时候就可以添加 Vue3.x 提供的 全局异常处理器,更清晰的 输出错误内容和调用栈信息,代码如下:
// main.ts
app.config.errorHandler = ( err, vm, info) => {
console.log( '[全局异常]', err, vm, info)
}
这时候就能看到输出内容如下:

文章插图
一下子就清楚很多 。当然,该配置项也可以用来集成错误追踪服务 Sentry 和 Bugsnag 。推荐阅读:Vue3 如何实现全局异常处理?
7. 观察 ref 的数据不直观,不方便
当我们在控制台输出 ref声明的变量时 。
constcount = ref<numer>( 0);
console.log( '[测试 ref]', count)
会看到控制台输出了一个 RefImpl对象:

推荐阅读
- 配音|余生,做一个能扛事的成年人
- 穿衣搭配|毛阿敏审美挺个性,戴发带混搭健美裤,变健美女孩太有朝气像30岁
- 幼儿园园长年终个人工作总结 幼儿园园长述职报告
- 鲜枣和干枣哪个好
- 清蒸素菜做法大全家常
- 香奈儿|一个半月,马思纯减掉20斤,潘玮柏减掉26斤,明星减肥为何很容易
- 壮族三月三的风俗习惯有哪些? 三月三是哪个民族的节日
- 四大洋中面积最小的是哪个 四大洋面积最小的是哪一个
- 火爆腰花的做法
- |逆向思维:不要再努力的学习和工作,这是一个天大的错误
