主题
Vue 3 API 速查
汇总 Vue 3 的全局 API、组合式 API、选项式 API、内置指令与内置组件,以及相对 Vue 2 的差异与移除项。 官方文档:内置组件、组合式 API。
一、全局 API
1. app.mount
将应用实例挂载在一个容器元素中:
ts
import { createApp } from "vue";
const app = createApp(/* ... */);
app.mount("#app");2. app.unmount
卸载一个已挂载的应用实例。
使用场景:微前端。
3. app.component
注册或获取组件。
使用场景:组件库开发。
ts
import { createApp } from "vue";
const app = createApp({});
// 注册一个选项对象
app.component("my-component", {
/* ... */
});
// 得到一个已注册的组件
const MyComponent = app.component("my-component");4. app.onUnmount()
3.5+,注册一个回调函数,在应用卸载时调用:
ts
interface App {
onUnmount(callback: () => any): void;
}5. app.use
安装一个插件。插件是一个拥有 install 方法的对象,也可以直接是一个安装函数本身:
js
// 拥有 install 方法的对象
const myPlugin = {
install(app, options) {
// 配置此应用
},
};
// 函数本身6. app.directive
注册或获取全局指令。
1. 新建 directive/index.ts
ts
import { App } from "vue";
export default function myDirective(app: App) {
app.directive("title", {
created(_, binding) {
document.title = binding.value;
},
});
}2. 在 main.ts 中引入
ts
import myDirective from "./directive";
app.use(myDirective);3. 在组件中使用
vue
<template>
<div v-title="title" class="login"></div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const title = ref("登录");
</script>4. 指令的生命周期
ts
created(el, binding, vnode, prevVnode) {},
beforeMount() {},
mounted() {},
beforeUpdate() {}, // 新增
updated() {},
beforeUnmount() {}, // 新增
unmounted() {}7. app.provide
提供一个固定值,可以在应用中的所有后代组件中注入使用。
1. 在 main.ts 中提供
ts
import { createApp } from "vue";
const app = createApp(/* ... */);
app.provide("message", "hello");2. 在组件中使用
vue
<script setup lang="ts">
defineOptions({
inject: ["message"],
mounted() {
// @ts-ignore
console.log(this.message); // 'hello'
},
});
</script>8. app.config.errorHandler
用于为应用内抛出的未捕获错误指定一个全局处理函数。
使用场景:错误收集。
ts
app.config.errorHandler = (err, instance, info) => {
// 处理错误,例如:报告给一个服务
};9. app.config.globalProperties
添加一个全局属性,所有组件实例都可以访问。
1. 修改 main.ts
ts
// 一般通过 $ 命名全局属性
app.config.globalProperties.$msg = "全局属性";2. 在组件中使用
vue
<script setup lang="ts">
import { getCurrentInstance, ComponentInternalInstance } from "vue";
// proxy 就是当前组件实例
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 全局注册的属性都能在当前组件实例上找到
console.log(proxy.$msg);
</script>提示:不建议使用
getCurrentInstance,这是 Vue 内部 API,可能会被更改。全局属性也可以加到window上(如果项目 Vue 版本不升级的话,可以使用)。
10. nextTick
将回调推迟到下一个 DOM 更新后执行,用于立即获取更新后的 DOM:
vue
<template>
<div>
<div id="count">{{ count }}</div>
<button @click="add">按钮</button>
</div>
</template>
<script setup lang="ts">
import { ref, nextTick } from "vue";
const count = ref(0);
const add = () => {
count.value++;
console.log(document.querySelector("#count")?.textContent); // DOM 未更新,0
nextTick(() => {
console.log(document.querySelector("#count")?.textContent); // DOM 已更新,1
});
};
</script>二、组合式 API
reactive更推荐用来定义对象,ref更推荐用来定义基础数据类型(ref也可以定义数组和对象,内部会使用reactive处理)。
1. ref
在模板或选项式 API 中使用 ref 定义的变量不需要加 .value,因为编译时会自动解包。
1. 值 ref
ts
import { ref } from "vue";
const initCode = ref("200");2. 模板 ref
html
<img ref="el" class="logo" :src="Logo" alt="" />ts
const el = ref(null);3.5+ 新增 useTemplateRef,可以更直观方便地操作 DOM:
html
<input ref="inputRef" />ts
const inputEl = useTemplateRef<HTMLInputElement>("inputRef");3. 组件 ref
html
<HelloWorld ref="helloWorldRef" />ts
const helloWorldRef = ref(null);3.5+ 新增 useTemplateRef,可以更直观方便地操作子组件:
html
<HelloWorld ref="helloWorldRef" />ts
const childRef = useTemplateRef("helloWorldRef");2. reactive
返回一个对象的响应式代理:
ts
import { reactive } from "vue";
const user = reactive({
name: "前端开发爱好者",
age: "20",
});3. computed
返回一个只读的响应式 ref 对象:
ts
const user = computed(() => {
return "前端开发";
});
console.log(user.value);访问旧值:计算属性的 getter 会收到上一次的计算结果。
vue
<script setup>
import { ref, computed } from "vue";
const count = ref(2);
// 这个计算属性在 count 的值小于或等于 3 时,将返回 count 的值。
// 当 count 的值大于等于 4 时,将会返回满足我们条件的最后一个值,
// 直到 count 的值再次小于或等于 3 为止。
const alwaysSmall = computed((previous) => {
if (count.value <= 3) {
return count.value;
}
return previous;
});
</script>4. watchEffect
1. 立即执行,自动追加依赖
使用到哪一层,就监听到哪一层:
ts
const count = ref(0);
watchEffect(() => console.log(count.value));
// -> logs 0
count.value++;
// -> logs 12. 默认在组件渲染之前执行
vue
<template>
<div ref="root">This is a root element</div>
</template>
<script setup lang="ts">
import { ref, watchEffect } from "vue";
const root = ref(null);
watchEffect(() => {
console.log(root.value); // => 先 null,之后拿到 DOM
});
</script>3. 暂停与恢复
3.5+ 中可暂停 / 恢复侦听器:
ts
const { stop, pause, resume } = watchEffect(() => {});
// 暂停侦听器
pause();
// 稍后恢复
resume();
// 停止
stop();5. watchPostEffect
在 DOM 更新后执行。
6. watchSyncEffect
在依赖改变时立即执行(例如要使缓存失效)。
7. watch
手动添加依赖,默认懒执行。
1. 监听 ref
ts
// 监听 ref
const count = ref(0);
watch(count, (count, prevCount) => {
/* ... */
});监听 ref 时默认不会深度监听,需手动开启:
ts
watch(
obj1,
(count, prevCount) => {
/* ... */
},
{
deep: true,
},
);3.5+ 中 deep 除了传入布尔值,还可以传入数字,代表监听到对象第几层。
2. 监听 reactive
当直接侦听一个响应式对象时,侦听器会自动启用深层模式:
ts
const state = reactive({ count: 0 });
watch(state, (curState, preState) => {
// 由于深层级的变更而被触发,新值和旧值将是同一个对象
console.log(curState.count === preState.count); // true
});3. 监听多个数据源
回调函数接受两个数组,分别对应来源数组中的新值和旧值:
ts
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
});4. 立即执行
ts
watch(
count,
(count, prevCount) => {
/* ... */
},
{
immediate: true,
},
);5. 暂停与恢复
Vue 3.5+ 中可暂停 / 恢复侦听器:
ts
const { stop, pause, resume } = watch(() => {});
// 暂停侦听器
pause();
// 稍后恢复
resume();
// 停止
stop();6. 只监听一次
3.4+ 中传入 once,侦听器将在回调函数首次运行后自动停止:
ts
watch(
source,
(newValue, oldValue) => {
// 当 `source` 变化时,仅触发一次
},
{ once: true },
);8. toRef
基于响应式对象上的一个属性,创建一个对应的 ref,这样创建的 ref 与其源属性保持同步:
ts
const state = reactive({
foo: 1,
bar: 2,
});
const fooRef = toRef(state, "foo");
// 更改该 ref 会更新源属性
fooRef.value++;
console.log(state.foo); // 2
// 更改源属性也会更新该 ref
state.foo++;
console.log(fooRef.value); // 3使用场景:将响应式对象的某个属性传递给函数,并且保持其引用。
js
setup(props) {
useSomeFeature(toRef(props, 'foo'))
}9. toRefs
将响应式对象转为普通对象,其中每个属性都指向源对象相应属性的 ref,每个独立的 ref 都是由 toRef() 创建的。
对自定义响应式数据解构:
ts
function useFeatureX() {
const state = reactive({
foo: 1,
bar: 2,
});
// 返回时转换为 ref(引用)
return toRefs(state);
}
// 可以在解构时不丢失响应性
const { foo, bar } = useFeatureX();10. shallowReactive
一个浅层 reactive,只监听第一层数据的变化(用于性能优化):
ts
const state = shallowReactive({
foo: 1,
nested: {
bar: 2,
},
});
// 更改状态自身的属性是响应式的
state.foo++;
// ...但下层嵌套对象不会被转为响应式
isReactive(state.nested); // false
// 不是响应式的
state.nested.bar++;11. customRef
创建一个自定义的 ref,显式声明对其依赖追踪和更新触发的控制方式:
ts
// 创建一个防抖 ref,即只在最近一次 set 调用后的一段固定间隔后再调用
import { customRef } from "vue";
export function useDebouncedRef(value, delay = 200) {
let timeout;
return customRef((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
},
};
});
}在组件中使用:
vue
<script setup>
import { useDebouncedRef } from "./debouncedRef";
const text = useDebouncedRef("hello");
</script>
<template>
<input v-model="text" />
</template>12. markRaw
标记一个对象,使其永远不会转换为 proxy,返回对象本身:
ts
const foo = markRaw({});
// isReactive:检查对象是否是由 reactive 创建的响应式代理
console.log(isReactive(reactive(foo))); // false使用场景:
- 有些值不应该是响应式的,例如复杂的第三方类实例
- 当渲染具有不可变数据源的大列表时,跳过 proxy 转换可以提高性能
13. 生命周期钩子
组合式 API 的生命周期钩子以 on 为前缀,例如 mounted → onMounted。
| 选项式 API | 组合式 API |
|---|---|
beforeCreate | setup(比 beforeCreate 更早) |
created | — |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
keep-alive 的两个生命周期:
| 选项式 API | 组合式 API |
|---|---|
activated | onActivated |
deactivated | onDeactivated |
14. provide / inject
组合式 API 的 provide / inject 是响应式的:provide 的值改变时,inject 的值也一同改变并更新视图。
1. provide
ts
const state = ref(0);
const handlerState = () => {
state.value = 1;
};
provide("info", state); // 提供响应式对象
provide("func", handlerState); // 提供改变响应式对象的方法2. inject
注入一个由祖先组件供给的值:
ts
const state = inject("info");
const func = inject("func");inject 的第二个参数是可选的,即没有匹配时使用的默认值:
ts
// 注入一个值,若为空则使用提供的默认值
const bar = inject("foo", "default value");15. onWatcherCleanup
3.5+ 新增的全局 API,在侦听器中注册清理回调函数:
ts
import { watch, onWatcherCleanup } from "vue";
watch(id, (newId) => {
const controller = new AbortController();
fetch(`/api/${newId}`, { signal: controller.signal }).then(() => {
// callback logic
});
onWatcherCleanup(() => {
// abort stale request
controller.abort();
});
});三、选项式 API
1. name
用于显式声明组件展示时的名称:
js
export default {
name: "MyComponent",
};2. components
一个对象,用于注册对当前组件实例可用的组件。
3. emits
声明由组件触发的自定义事件:
js
export default {
emits: ["check"],
created() {
this.$emit("check");
},
};4. expose
声明当组件实例被父组件通过模板引用访问时暴露的公共属性:
js
export default {
// 只有 `publicMethod` 在公共实例上可用
expose: ["publicMethod"],
methods: {
publicMethod() {
// ...
},
privateMethod() {
// ...
},
},
};5. provide / inject
选项式 API 的 provide / inject 是非响应式的。
1. provide
js
provide() {
return {
foo: 'msg',
}
},2. inject
js
export default {
inject: ["foo"],
created() {
console.log(this.foo);
},
};6. props
接收来自父组件的数据:
js
props: ["height", "size"];7. data
用于声明组件初始响应式状态的函数:
js
data() {
return { a: 1 }
}8. computed
计算属性基于响应式依赖进行缓存,只有依赖改变时才会重新求值:
js
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
},
},9. watch
监听器。
1. 默认懒执行
当值改变时才开始执行监听函数,第一次绑定时不执行:
js
watch: {
inputValue(newVal, oldVal) {},
},2. 立即执行
如果想第一次绑定值时就执行监听函数,需用到 handler 方法和 immediate 属性:
js
watch: {
inputValue: {
handler(newVal, oldVal) {
console.log(newVal, oldVal)
},
immediate: true,
},
},3. 深度监听
普通的 watch 方法无法监听到对象内部属性值的改变;如果整个对象被重新赋值(例如 this.obj = { a: '12' }),则不需要深度监听。
js
watch: {
user: {
handler(newVal, oldVal) {
console.log(newVal, oldVal)
},
deep: true,
},
},提示:在组合式 API 中,
watch监听reactive定义的变量会自动开启深度监听。
4. 监听对象中某个属性
js
watch: {
'user.age': {
handler(newVal, oldVal) {
console.log(newVal, oldVal)
},
},
},10. directives
局部自定义指令:
js
export default {
directives: {
// 在模板中启用 v-focus
focus: {
mounted(el) {
el.focus();
},
},
},
};html
<input v-focus />11. methods
注意,不应该使用箭头函数来定义 method 函数(例如 plus: () => this.a++)。箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined。
js
methods: {
plus() {
this.a++
},
},12. 组件实例
1. $refs
一个包含 DOM 元素和组件实例的对象,通过模板引用注册:
vue
<template>
<div ref="dom">dom 区域</div>
</template>
<script lang="ts">
export default {
mounted() {
console.log(this.$refs.dom);
},
};
</script>ref:用于注册模板引用。
2. $attrs
没有通过 props 接收的属性,都能在 this.$attrs 中访问到;可以通过 v-bind="$attrs" 把父组件传递的属性和方法全部传给自己的子组件。
html
<!-- 父组件 -->
<HelloWorld :msg="msg"></HelloWorld>
<!-- 子组件 -->
<child v-bind="$attrs"></child>js
// 孙子组件
props: {
msg: {
type: String,
},
},3. $emit
在当前组件触发一个自定义事件:
js
this.$emit("check", obj);4. $nextTick
js
this.$nextTick(() => {});四、内置指令
1. v-text
更新元素的文本内容(等同于 ):
html
<span>{{ msg }}</span>2. v-html
更新元素的 innerHTML:
html
<div v-html="html"></div>3. v-show
通过设置内联样式的 display: none 来工作。
4. v-if
当 v-if 元素被触发时,元素及其所包含的指令 / 组件都会销毁和重建。
5. v-else
html
<div v-if="Math.random() > 0.5">Now you see me</div>
<div v-else>Now you don't</div>6. v-else-if
html
<div v-if="type === 'A'">A</div>
<div v-else-if="type === 'B'">B</div>
<div v-else-if="type === 'C'">C</div>
<div v-else>Not A/B/C</div>7. v-for
1. 遍历数组
html
<div v-for="item in items" :key="item.id">{{ item.text }}</div>2. 遍历对象
html
<div v-for="(value, name, index) in object"></div>8. v-on
给元素绑定事件监听器(等同于 @):
html
<button @click="doThis"></button>9. v-bind
动态地绑定一个或多个 attribute,也可以是组件的 prop(等同于 :):
html
<!-- 缩写 -->
<img :src="imageSrc" />
<!-- 绑定对象形式的 attribute -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
<!-- 传递父子组件共有的 prop -->
<MyComponent v-bind="$props" />
<!-- class 绑定 -->
<div class="static" :class="{ activeClass: isActive }"></div>
<div :class="[isActive ? 'activeClass' : 'errClass', 'comClass']"></div>
<!-- style 绑定 -->
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>在 Vue 3.4+ 中,如果 attribute 的名称与绑定的 JavaScript 变量名称相同,可以进一步简化语法,省略 attribute 值:
html
<!-- 与 :id="id" 相同 -->
<div :id></div>10. v-model
在表单输入元素或组件上创建双向绑定:
html
<input v-model="value" />11. v-slot
用于声明具名插槽或作用域插槽(等同于 #)。
1. 匿名插槽
html
<!-- 父组件 -->
<HelloWorld>
<p>我是匿名插槽</p>
</HelloWorld>
<!-- 子组件 -->
<slot>我是插槽默认值</slot><slot>:表示模板中的插槽内容出口。
2. 具名插槽
通过 name 定义插槽位置:
html
<!-- 父组件 -->
<HelloWorld>
<template #todo>
<p>我是具名插槽</p>
</template>
</HelloWorld>
<!-- 子组件 -->
<slot name="todo">我是默认值</slot>3. 作用域插槽
父组件可以访问子组件的数据:
html
<!-- 父组件 -->
<HelloWorld>
<template #todo="{ user }">{{ user.age }}</template>
</HelloWorld>
<!-- 子组件 -->
<template>
<div>
子组件
<slot :user="user" name="todo"></slot>
</div>
</template>js
export default {
data() {
return {
user: {
age: 2,
},
};
},
};12. v-pre
跳过该元素及其所有子元素的编译:
html
<!-- 显示原始双大括号标签及内容 -->
<span v-pre>{{ this will not be compiled }}</span>13. v-once
仅渲染元素和组件一次,并跳过之后的更新:
html
<!-- 单个元素 -->
<span v-once>This will never change: {{ msg }}</span>
<!-- 组件 -->
<MyComponent v-once :comment="msg" />
<!-- v-for 指令 -->
<ul>
<li v-for="i in list" v-once>{{ i }}</li>
</ul>14. v-memo
缓存一个模板的子树,除非依赖项变更:
html
<div v-memo="[valueA, valueB]">...</div>
<!-- 与 v-for 一起使用 -->
<div v-for="item in list" :key="item.id" v-memo="[item.id === selected]">
<p>ID: {{ item.id }} - selected: {{ item.id === selected }}</p>
<p>...more child nodes</p>
</div>五、内置组件
1. Transition
为单个元素或组件提供动画过渡效果(路由组件不能使用片段,否则动画效果无法展示):
vue
<template>
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</template>
<style>
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.fade-enter-to,
.fade-leave-from {
transition: opacity 0.2s ease;
}
</style>2. TransitionGroup
为列表中的多个元素或组件提供过渡效果:
html
<TransitionGroup tag="ul" name="slide">
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</TransitionGroup>3. KeepAlive
缓存组件,在路由切换时保存组件内的状态。
新增两个生命周期:activated 和 deactivated。
属性:
include:字符串或正则表达式。只有名称匹配的组件会被缓存。exclude:字符串或正则表达式。匹配的组件不会被缓存。max:数字。超过这个缓存数,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。
用 include 的方式引入,需要组件上有 name 属性:
js
export default {
name: "HelloWorld", // 在组件中定义 name 值,不是在路由里定义
data() {
return {};
},
};html
<router-view v-slot="{ Component }">
<Transition name="fade" mode="out-in">
<KeepAlive :include="keepList" :exclude="exList" :max="8">
<component :is="Component" />
</KeepAlive>
</Transition>
</router-view>4. Teleport
将组件挂载到父组件之外的 DOM 节点:
html
<!-- index.html -->
<div id="app"></div>
<div id="teleport-target"></div>html
<template>
<!-- to 属性就是目标位置 -->
<teleport to="#teleport-target">
<div v-if="visible" class="toast-wrap">
<div class="toast-msg">我是一个 Toast 文案</div>
</div>
</teleport>
</template>5. Suspense(实验)
<Suspense> 组件有两个插槽,分别对应 default 和 fallback 两种状态。
异步组件(defineAsyncComponent 或 async setup)加载时呈现 fallback 插槽,加载完成后呈现 default 插槽。
父组件:
vue
<template>
<div>
<Suspense>
<template #default>
<HelloWorld />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</div>
</template>
<script lang="ts" setup>
import HelloWorld from "./components/HelloWorld.vue";
</script>子组件:
vue
<template>
<div class="text">{{ data }}</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const loadData = () => {
return new Promise<string>((resolve) => {
setTimeout(() => {
resolve("hello");
}, 3000);
});
};
const data = ref("");
const res = await loadData();
data.value = res;
</script>组件调用顺序:
html
<RouterView v-slot="{ Component }">
<template v-if="Component">
<Transition mode="out-in">
<KeepAlive>
<Suspense>
<!-- 主要内容 -->
<component :is="Component"></component>
<!-- 加载中状态 -->
<template #fallback>正在加载...</template>
</Suspense>
</KeepAlive>
</Transition>
</template>
</RouterView>6. component
一个用于渲染动态组件或元素的「元组件」:
vue
<script>
import Foo from "./Foo.vue";
import Bar from "./Bar.vue";
export default {
components: { Foo, Bar },
data() {
return {
view: "Foo",
};
},
};
</script>
<template>
<component :is="view" />
</template>is:用于绑定动态组件。
7. template
当我们想要使用内置指令而不在 DOM 中渲染元素时,<template> 标签可以作为占位符使用。
对 <template> 的特殊处理只有在它与以下任一指令一起使用时才会被触发:v-if、v-else-if、v-else、v-for、v-slot。
如果这些指令都不存在,那么它将被渲染成一个原生的 <template> 元素。
六、script setup 与 TypeScript
待补充:<script setup> 的编译宏(defineProps、defineEmits、defineExpose 等)与 TypeScript 类型写法。
七、CSS 相关
1. 组件作用域 CSS
1. scoped 样式只会影响当前组件
vue
<style scoped>
.example {
color: red;
}
</style>
<template>
<div class="example">hi</div>
</template>编译为:
vue
<style>
.example[data-v-f3f3eg9] {
color: red;
}
</style>
<template>
<div class="example" data-v-f3f3eg9>hi</div>
</template>使用 scoped 后,父组件的样式将不会渗透到子组件中。不过,子组件的根节点会同时被父组件的作用域样式和子组件的作用域样式影响。
2. 混合使用局部与全局样式
vue
<style>
/* 全局样式 */
</style>
<style scoped>
/* 局部样式 */
</style>3. 样式穿透
如果想影响到子组件,可以使用 :deep() 这个伪类:
vue
<style lang="scss" scoped>
// 这样写不生效的话
.el-form {
.el-form-item { ... }
}
// Vue 3 中这样写
:deep(.el-form) {
.el-form-item { ... }
}
</style>2. CSS Modules
一个 <style module> 标签会被编译为 CSS Modules,并且将生成的 CSS class 作为 $style 对象暴露给组件:
vue
<template>
<p :class="$style.red">This should be red</p>
</template>
<style module>
.red {
color: red;
}
</style>3. 动态 CSS
通过 v-bind 将状态值绑定到 CSS 样式上:
vue
<script setup>
const theme = {
color: "red",
};
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
color: v-bind("theme.color");
}
</style>八、与 Vue 2 的差异
1. 响应式实现
Vue 3 使用 Proxy 实现响应式,能直接侦测对象属性的新增 / 删除、数组索引赋值和长度变化,因此不再需要 Vue.set / Vue.delete(见下文「移除 $set 和 $delete」)。
注意:DOM 更新依然是异步批量的。修改数据后立即读取 DOM 仍会拿到旧值,需要用
nextTick等待更新完成(见「全局 API → nextTick」)。
九、从 Vue 2 移除的 API
1. 移除 .native 修饰符
v-on.native 的作用:将原生 DOM 监听器添加到子组件的根元素中。
移除目的:确保所有组件都使用 emits 选项记录事件。
兼容方案:想监听第三方组件根元素的原生 DOM 事件,可以在外面再套一层 div;自定义组件使用 emits 选项记录,通过 emit 触发事件。
2. 移除 keyCodes
Vue 2 中:
html
<!-- 键码版本 -->
<input v-on:keyup.13="submit" />
<!-- config.keyCodes 版本 -->
<input v-on:keyup.f1="showHelpText" />js
Vue.config.keyCodes = {
f1: 112,
};Vue 3 中:直接将 KeyboardEvent.key 暴露的任意有效按键名转换为 kebab-case 作为修饰符:
html
<input @keyup.page-down="onPageDown" />3. 移除 $on、$off、$once
意味着事件总线不能再使用。
替代方案:使用外部事件中心库 mitt 或 tiny-emitter。
安装:
bash
npm install --save mitt使用:
js
// eventBus.js
import mitt from "mitt";
const bus = {};
const emitter = mitt();
bus.$on = emitter.on;
bus.$off = emitter.off;
bus.$emit = emitter.emit;
export default bus;js
// 父组件
import bus from "../eventBus";
export default {
name: "Home",
methods: {
handleClick() {
bus.$emit("page1", "消息");
},
},
};js
// 子组件
import bus from "../eventBus";
export default {
mounted() {
bus.$on("page1", (msg) => {
console.log(msg);
});
},
beforeUnmount() {
bus.$off("page1");
},
};4. 移除 filters
过滤器已移除,因为它不符合 中只有 JavaScript 表达式的思想,可以用计算属性替代:
vue
<template>
<h1>Bank Account Balance</h1>
<p>{{ accountInUSD }}</p>
</template>
<script>
export default {
props: {
accountBalance: {
type: Number,
required: true,
},
},
computed: {
accountInUSD() {
return "$" + this.accountBalance;
},
},
};
</script>对于全局过滤器,可以通过全局属性去定义方法:
js
// main.js
const app = createApp(App);
app.config.globalProperties.$filters = {
currencyUSD(value) {
return "$" + value;
},
};然后在模板中通过 $filters 对象使用:
vue
<template>
<h1>Bank Account Balance</h1>
<p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>5. 移除 $set 和 $delete
由于 Vue 3 使用 Proxy 进行代理,基于代理的变化检测已经不需要它们了。